检查特定HTML标记的wordpress帖子。否则显示帖子缩略图

时间:2015-10-24 10:46:49

标签: php wordpress if-statement thumbnails nextgen-gallery

我想这个问题之前一定是问过这个问题,但我找不到这个话题,所以请耐心等待。

我正在尝试在PHP中实现if / else语句,以查找具有特定类名的特定HTML标记。如果找到此HTML标记,我希望它显示HTML标记,否则如果找不到,我希望它显示帖子缩略图。

所有这些都需要在wordpress模板(single.php)中完成。

所以我有这个:

if (strpos($post->post_content, ('img[.ngg_displayed_gallery]') === false)){
        $gallery = false;
          the_post_thumbnail('full');
          echo do_shortcode('[shareaholic app="share_buttons" id="390155"]');
        }
else{
    echo ('img[.ngg_displayed_gallery]');
    echo do_shortcode('[shareaholic app="share_buttons" id="390155"]');
    }

我很确定我搞砸了这个代码所以请帮助我。我对PHP非常糟糕;)

感谢您的帮助! 编辑:

好的..我会尝试更清楚: 当有人编辑wordpress帖子并在内容编辑器中添加Nextgen Gallery时,会出现以下HTML字符串:

<img class="ngg_displayed_gallery mceItem" src=“../nextgen-attach_to_post/preview/id--1443" alt="" data-mce-placeholder="1" /> 

所以基本上我想编写类似这样的代码:当这个HTML IMG字符串出现在内容字段中时,显示后缩略图的INSTEAD(特色图像)..如果该HTML IMG字符串不在内容字段中,则显示帖子缩略图(特色图片)。

1 个答案:

答案 0 :(得分:1)

根据我对这个问题的理解,你需要在字符串的内容中找到一个html标签,你正在使用strpos()。我想告诉您这是不良做法,应该使用替代方案,但是,这是一个例子。

// First we must get the HTML formated content.
$content = apply_filters ("the_content", $post->post_content);

// We then must indentifie the needle in the heystack (content)
$needle = 'ngg_displayed_gallery';

if (strpos($content, $needle) === false)){
    $gallery = false;
    // No, there's no gallery present
    echo "NO, gallery not found";
} else {
    // Yes there is an gallery present
    echo "YES, gallery found"; 
}

<强> Q1。为什么这是不好的做法?

我们可以找到图库/图片可靠性的ID,因为每个<img class='ngg_displayed_gallery'..>srcidclass < / p>