2013-12-18 82 views
3

我有一個字符串,可能包含諸如「這是一個帶[anyshortcode1]的字符串,這是[anyshortcode2]」的簡碼。我想顯示字符串,其中包含放置它們的簡碼。當我回顯這個字符串時,它不會執行簡碼,只是將它們打印出來放在括號中。我試圖通過使用如下代碼來解決這個問題:在字符串中執行WordPress簡碼

$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; 

這成功地做字符串替換,但會導致錯誤與eval函數:

Parse error: syntax error, unexpected T_STRING

我使用eval函數錯了嗎?還是有一種更簡單的方法來完成從字符串運行短代碼?

回答

8

爲了在字符串內執行shortcode,您必須使用do_shortcode()函數。

這是如何使用它:

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

如果這不起作用,那麼什麼不對您的安裝。請注意,eval()不是您的代碼中最好的命令。 :)

最後確保短碼仍然存在。有許多主題使用短代碼來設計內容樣式,然後,當用戶安裝另一個主題時,之前的短代碼不再有效,因爲它們將被移除以前的主題。

+1

哇謝謝你!我這樣做太複雜了。我誤解了do_shortcode的工作方式。 – tcox

+0

如果您找到答案,請將其標記爲答案。這樣你可以節省其他StackOverflow的使用時間;)啊...並歡迎來到WordPress的世界! :) –

+0

此外,如果你有'$ str ='

[shortcode]
''這樣的東西,它也可以工作,如果你使用'echo do_shortcode($ str)' – mapmalith

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

我不確定你想用Eval做什麼。