【问题标题】:Wordpress: How to add_filter to a special div of the_contentWordpress:如何将_filter 添加到 the_content 的特殊 div
【发布时间】:2013-06-05 23:59:36
【问题描述】:

我正在尝试将过滤器添加到我的 wordpress 内容的特殊 div

确定我的插件代码现在将影响所有帖子内容,但我需要将它仅应用于特殊的 div class="game_req" 而不是其他 div 前。 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');

【问题讨论】:

  • 我找到了 body_class 过滤器,但我不知道它是否与为 ex 的特殊 div 添加特殊效果有关。
  • 我想知道,这个问题真的很难,所以没有人知道答案或给我提示
  • @Tim 就是这样,我在想你会解决我的问题 :D,但是 [已解决] 或已解决.. 是否违反网站规则?

标签: php wordpress html preg-replace


【解决方案1】:

因为没有人回答我的问题,所以我决定尝试多种方法自己解决我的问题

最后的解决办法是:

我不应该使用 add_filter ,而是必须使用 add_shortcode 更改只是替换

 function myReplace_function($content){

 function myReplace_function($attrs,$content=none){

还添加任何特定代码作为简码 ex。 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]

就是这样。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签