tcox tcox - 3 months ago 20
PHP Question

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?


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.