我正在尝试仅向我的 WordPress 内容的特殊 div 添加过滤器
现在我的插件代码肯定会影响所有帖子内容,但我需要的是仅将其应用于特殊的 div class="game_req" 而不是其他 div ex。 div class="how_to_play"
我的帖子结构:
<div>
..........
<div class="game_req"> <!-- i need to apply filter to only this div -->
- ball : is a round ..........
- key : is what we need to ..........
- caw : is an animal ..........
</div>
<div class="how_to_play">
1- use the key to open .......
2- use ball to ........
3- use caw to .........
</div>
<div class="sss">
.... key .......
.... ball to ........
.... caw .........
</div>
..........
</div>
我的插件过滤器:
function myReplace_function($content){
$patterns = array(
'/\bball\b/',
'/\bkey\b/',
'/\bcaw\b/'
);
$replacements = array(
'ball ( <img src="smallImgs/ball.png" alt="ball"/> )',
'key ( <img src="smallImgs/key.png" alt="key"/> )',
'caw ( <img src="smallImgs/caw.png" alt="caw"/> )'
);
return preg_replace($patterns,$replacements,$content);
}
add_filter('the_content','myReplace_function');
最佳答案
因为没有人回答我的问题,所以我决定尝试多种方法自己解决我的问题
最终解决方案是:
我不应该使用 add_filter ,而是必须使用 add_shortcode 唯一的变化是替换
function myReplace_function($content){
与
function myReplace_function($attrs,$content=none){
还添加任何特定代码作为短代码例如。 my_shortcode
而不是 the_content
所以我的函数应该是这样的
function myReplace_function($attrs,$content=none){
$patterns = array(
'/\bball\b/',
'/\bkey\b/',
'/\bcaw\b/'
);
$replacements = array(
'ball ( <img src="smallImgs/ball.png" alt="ball"/> )',
'key ( <img src="smallImgs/key.png" alt="key"/> )',
'caw ( <img src="smallImgs/caw.png" alt="caw"/> )'
);
return preg_replace($patterns,$replacements,$content);
}
add_shortcode('my_shortcode','myReplace_function');
最后我可以通过包装我的帖子内容的任何部分来使用它[my_shortcode]...[/my_shortcode]
所以如果我将其应用到我的问题示例中,它将如下所示:
[my_shortcode]<div class="game_req"> <!-- i need to apply filter to only this div -->
- ball : is a round ..........
- key : is what we need to ..........
- caw : is an animal ..........
</div>[/my_shortcode]
仅此而已。
关于php - WordPress:如何将_filter添加到the_content的特殊div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17022033/