php - WordPress:如何将_filter添加到the_content的特殊div

标签 php wordpress html preg-replace

我正在尝试仅向我的 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/

相关文章:

php - Laravel - 查询 "with"

php - WooCommerce:返回特定类别中所有产品 ID 的函数

MySQL时间戳默认值无效

html - 定制的 Twitter Bootstrap 3 Carousel 添加垂直/水平滚动条

php - 该值在表中,但所选值为 NULL

php - 如何显示来自 mySQL 数据库的两个单独表的值?

css - z-index 在下拉菜单的 Wordpress 主题中不起作用

javascript - 即使在 wp_register_script 依赖项数组中定义,jQuery 也未在 WordPress 主题中定义

javascript - 为什么 DOM 对象在控制台中的显示与一般 Javascript 对象不同?

php - html/php 随机图像生成器 - 根据屏幕尺寸对齐图像