[英]Shortcode is moving the_content outside of the article container in WordPress
[英]Wordpress shortcode filtering the_content modifies all posts in a list
我正在寫一個插件,並且代碼如下:
add_shortcode('test','testfunc');
function testfunc(){
add_filter('the_content','mycontent',20);
}
function mycontent($content){
return "<p style='color:red'>extra content</p>";
}
我在我的一個帖子上使用了短代碼'[test]'。
問題是當顯示帖子列表時 - 例如使用類別視圖時 - 顯示所有顯示的帖子的內容 - 而不僅僅是包含短代碼的帖子。
任何想法如何我可以改變它所以它只過濾代碼
嗨繼承人解決方案是不使用短代碼鈎子,但它在內容中搜索它。
function content_custom_shortcode($content) {
// Search for shortcode
$shortcode = 'test';
preg_match('/\['.$shortcode.'\]/s', $content, $matches);
// If custom shortcode exists return custom content else return content
if (in_array('['.$shortcode.']', $matches)) return "<p style='color:red'>extra content</p>";
else return $content;
}
add_filter('the_content','content_custom_shortcode',20);
每當您顯示帖子列表並且其中一個包含您創建的短代碼時,它將更改顯示的所有后續帖子,因為您已將其添加到the_content
,這將在The Loop的每次迭代中執行。 刪除過濾器,它應該按預期工作。
這將使用[test]
和[/test]
包圍您在<p>
標記中包含的內容:
add_shortcode('test','testfunc');
function testfunc($atts, $content=NULL){
return "<p style='color:red'>{$content}</p>";
}
如果您想用替換文本替換帖子中的所有內容,請將上面示例中的變量{$content}
更改為您想要的任何文本。 您仍然需要在[test]
和[/test]
包含帖子內容。
關於短代碼的WordPress Codex條目中有一個與此非常相似的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.