Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing WordPress Shortcodes in a String

I have a string that may contain shortcodes such as "this is a string with [anyshortcode1] and this is [anyshortcode2]". I want to display the string with the shortcodes running where they are placed. When I echo this string out, it doesn't do the shortcodes, it just prints them out leaving them in brackets. I tried to fix this by using code like the following:

$string_with_shortcodes = "this is a string with [anyshortcode1] and this is [anyshortcode2]";
$pattern = get_shortcode_regex();
preg_match_all("/$pattern/",$string_with_shortcodes, $matches);
foreach ($matches[0] as $short) {
    $string_with_shortcodes = str_replace($short, 'do_shortcode("' . $short . '")', $string_with_shortcodes);
}
eval("\$string_with_shortcodes = \"$string_with_shortcodes\";");
echo $string_with_shortcodes;

This successfully does the string replacement, but causes an error with the eval function:

Parse error: syntax error, unexpected T_STRING

Am I using the eval function wrong? Or is there a simpler way to accomplish running shortcodes from a string?

like image 933
tcox Avatar asked Dec 18 '13 13:12

tcox


2 Answers

In order to execute the shortcode from within the string you have to use the do_shortcode() function.

This is how to use it:

$string_with_shortcodes = "this is a string with [anyshortcode1] and this is [anyshortcode2]";
echo do_shortcode($string_with_shortcodes);

If this does not work, then something wrong with your installation.

Also note, that eval() is not the best command in your code .. ! :)

Finally make sure that the shortcode still exists. There are many many themes that using shortcodes for styling the content, and then, when the user installs another theme, the previous shortcodes are not functional anymore, because they will be removed with the previous theme.

like image 117
KodeFor.Me Avatar answered Oct 19 '22 07:10

KodeFor.Me


$string_with_shortcodes = str_replace($short, do_shortcode($short), $string_with_shortcodes);

I am not sure what you are trying to do with Eval.

like image 23
Lucky Soni Avatar answered Oct 19 '22 06:10

Lucky Soni