过滤以检查关键字并相应地显示侧边栏内容

Sar*_*a44 0 php wordpress

在Wordpress中,是否可以阅读帖子的内容并查找关键词,然后相应地显示侧边栏内容?例:

如果帖子内容包含单词'cheese',则不显示侧栏广告,否则显示.

有关额外信息,我有> 500个帖子,因此不希望为每个帖子添加标签或自定义字段.

我将包含代码示例,但我真的不确定是否从functions.php中的正则表达式开始,如果是这样,那么我在侧边栏代码中寻找什么呢?

提前致谢.

更新1 - 对于这个目的,Stripos似乎比正则表达式更快在php.net上的应用程序所以我使用了这个.

更新2 - 我当前的设置...在index.php(或page.php等取决于主题):

    <?php
    if( has_keyword() ) {
        get_sidebar( 'special' );
    } else {
        get_sidebar( 'normal' );
    }
    ?>
Run Code Online (Sandbox Code Playgroud)

并在functions.php中

function has_keyword ()
{
    global $post;

    $mywords = array('word1', 'word2', 'word3');
    foreach($mywords as $word){

        // return false if post content does not contain keyword
        if( ( stripos( $post->post_content, $word ) === false ) ) {
        return false;
        };
    };
        // return true if it does
        return true;
}; //end function
Run Code Online (Sandbox Code Playgroud)

我需要让foreach函数工作,那里有一些错误.我尝试使用'break'成功找到一个单词,但我也需要返回'false',这就是我添加if条件的原因.不知道该怎么做.

dig*_*ggy 5

你可以使用PHP stripos.在functions.php:中定义自定义条件标签:

function has_keyword( $keyword )
{
    // only check on single post pages
    if( ! is_singular() )
        return false;

    global $post;

    // return false if post content does not contain keyword
    if( ( stripos( $post->post_content, $keyword ) === false ) )
        return false;

    // return true if it does
    return true;
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的模板文件中:

if( has_keyword( 'my_keyword' ) )
    get_sidebar( 'normal' );
else
    get_sidebar( 'special' );
Run Code Online (Sandbox Code Playgroud)

更新

要检查多个关键字(请参阅注释):

function has_keyword()
{
    if( ! is_singular() )
        return false;
    global $post;
    $keywords = array( 'ham', 'cheese' );
    foreach( $keywords as $keyword )
        if( stripos( $post->post_content, $keyword ) )
            return true;
    return false;
}
Run Code Online (Sandbox Code Playgroud)