WordPress相关的帖子错误

时间:2012-07-28 18:49:40

标签: php wordpress

我不仅在Google上搜索过,而且在其他地方搜索过,包括此处找不到任何可以帮助解决此问题的内容。

这是问题所在。我有一个基于标签而不是类别的相关帖子片段,我在WordPress主题中使用,我已经使用了很长一段时间,它的效果非常好。这是:

        $tags = wp_get_post_tags($post->ID);
    $tagIDs = array();
    if ($tags) {
        $tagcount = count($tags);
        for ($i = 0; $i < $tagcount; $i++) {
            $tagIDs[$i] = $tags[$i]->term_id;
        }
    $args=array(
    'tag__in' => $tagIDs,
    'post__not_in' => array($post->ID),
    'showposts'=>mytheme_option( 'related_count' ),
    'ignore_sticky_posts'=>1
    );
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
        echo '<h4>'. __('Other Posts You May Be Interested In', "themename"). ':</h4><ul>';
        while ($my_query->have_posts()) : $my_query->the_post(); ?>

            <li class="imglink">

                <!-- post loop stuff goes here -->

            </li>

<?php endwhile;
echo '</ul>';
}
else {
echo '<h4>'. __('Other Posts You May Be Interested In', "themename"). ':</h4>
'. __('<p>There are no related posts at this time.</p>', "themename"). '';
}   
}
$post = $original_post;
wp_reset_query();

就像我说的那样效果很好。如果帖子具有相同的标记,则会显示:

  

您可能感兴趣的其他帖子:   显示相同标签的帖子

但问题是:如果给一个帖子一个标签而其他帖子没有相同的标签,则显示如下:

  

您可能感兴趣的其他帖子:没有相关帖子   这一次。

现在,如果没有为帖子分配标签,则绝对不显示任何内容。相关帖子应该显示的div是空的,但应该说没有相关的帖子。

我已经找到了一个解决方案并尝试了许多不同的方法来纠正这个问题,但我似乎无法理解它。有人可以帮助我获得:

  

您可能感兴趣的其他帖子:没有相关帖子   这一次。

显示帖子没有标签。非常感谢任何帮助,非常感谢您。

1 个答案:

答案 0 :(得分:0)

我认为问题来自对函数顶部的条件:

$tags = wp_get_post_tags($post->ID);

$tagIDs = array();
if ($tags) {
    # All of your code is in this conditional, 
    # if there are no tags, nothing will happen
}

如果找不到帖子的标签,它会跳过所有代码并且不会渲染任何内容。只有当前帖子有标签时才会执行代码底部的else语句,但其他帖子中不包含该标签。

编辑,并根据请求提供示例 - 您需要有2个其他条件来回显无帖子内容,一个用于没有标签,一个用于是否有标签但是找不到帖子:

$tags = wp_get_post_tags($post->ID);

$tagIDs = array();
if ( count( $tags ) > 0) {
    // setup $tagIDs and perform query...

    if( $my_query->have_posts() ) {
        // Echo out posts.
    } else {
        echo '<h4>'. __('Other Posts You May Be Interested In', "themename"). ':</h4>
        '. __('<p>There are no related posts at this time.</p>', "themename"). '';
    }
} else {
    echo '<h4>'. __('Other Posts You May Be Interested In', "themename"). ':</h4>
    '. __('<p>There are no related posts at this time.</p>', "themename"). '';
}

应该这样做。不过,我建议将内容包装到函数中。然后你可以在功能结束时回显无帖子内容,如果找到帖子则回复“返回”。那你就不会重复自己了。