0

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

如果帖子内容包含“奶酪”一词,则不要显示侧边栏广告,否则显示。

有关更多信息,我有超过 500 个帖子,因此不想为每个帖子添加标签或自定义字段。

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

提前致谢。

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

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

4

3 回答 3

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;
}
于 2013-05-20T18:26:45.283 回答
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 中,你可以在你的Update中做你的大声思考。自然地更改函数名称以反映您对命名的选择。

于 2013-05-21T18:34:01.717 回答
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()以供参考 希望它有意义

于 2013-05-22T07:44:27.667 回答