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


Filter to check for keyword and display sidebar content accordingly

在Wordpress中,是否有可能阅读文章的内容并查找关键字,然后相应地显示侧边栏内容?例子:

如果帖子内容包含"cheese"这个词,那么不要显示侧边栏广告,否则显示。

对于额外的信息,我有>500个帖子,所以不想为每个帖子添加标签或自定义字段。

我包括代码的例子,但我真的不确定是否开始与一个正则表达式在函数。php,如果是这样的话,我在侧边栏的代码寻找什么?

提前感谢。

UPDATE 1 - Stripos在php.net上似乎比正则表达式更快,所以我使用了这个。

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

    <?php
    if( has_keyword() ) {
        get_sidebar( 'special' );
    } else {
        get_sidebar( 'normal' );
    }
    ?>

和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

我需要得到foreach函数工作,有一些错误在那里。我试图使用"break"成功找到一个词,但我需要返回"false",这就是为什么我添加了if条件。不知道该怎么做。

您可以使用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;
}

然后,在模板文件中:

if( has_keyword( 'my_keyword' ) )
    get_sidebar( 'normal' );
else
    get_sidebar( 'special' );

检查多个关键字(见注释):

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;
}

如果您想对单词列表进行验证,您可以使用下面的函数,如果在$content中找到任何单词,它将返回false,否则它将返回true。所以说,继续,显示他们的广告。

function displayAds($content){
    $words = array('cheese', 'ham', 'xxx');
    foreach($words as $word){
       if(preg_match('/'s'.$word.''s/i', $content)){
          return FALSE;
       };
    };
    return TRUE;
 };

,然后在你的index.php你可以做你的outloud思维在你的更新。自然地更改函数名以反映您选择的命名

您也可以使用preg_match在字符串中查找精确的关键字匹配,如

function check_keyword($keyword){
global $post;
if(!is_single() ){
return false;
}else{
$result = preg_match('/'b('.$keyword.')'b/', $post->post_content);
if($result){
return true;
}else{
return false;
}

}
}

得到side_bar

Call check_keyword()

if (check_keyword('cheese')) {
get_sidebar('cheese');
} else {
get_sidebar('no-ads');
} 

参见preg_match()