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

时间:2013-05-03 14:46:09

标签: php wordpress

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

如果帖子内容包含“cheese”字样,则不显示侧边栏广告,否则显示。

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

我会包含代码示例,但我真的不确定是否要在functions.php中使用正则表达式,如果是这样,那么我在侧边栏代码中会查找什么?

提前致谢。

更新1 - 出于此目的,Stripos似乎比正则表达式更快Stripos on php.net所以我使用了它。

更新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条件的原因。不知道该怎么做。

3 个答案:

答案 0 :(得分: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;
}

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

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

答案 1 :(得分:1)

如果你想要对一个单词列表进行验证,你可以使用下面的这个函数,如果在你的$ 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中,您可以在更新中做出明智的想法。自然更改函数名称以反映您的命名选择。

答案 2 :(得分:1)

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

致电check_keyword()

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

参考资料preg_match() 希望它有意义

相关问题