【问题标题】:Wordpress, related posts, get one of the post's categoriesWordpress,相关帖子,获取帖子的类别之一
【发布时间】:2015-11-20 14:25:58
【问题描述】:

我正在使用此代码显示相关帖子:

$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 5, 'post__not_in' => array($post->ID) ) );
?><h2> More from this category:</h2> <ul class="related-posts"> <?php
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?> 
        <li class="pov">
            <div class="ex-s1">
            <a href="<?php the_permalink();?>">
    <?php the_post_thumbnail(array(356, 220)); ?>
    </a> 
                </div>
            <div class="ex-n1">
        <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
            </div>
            <div class="ex-t1">
           <?php echo get_excerpt(250);?>
              </div>
        </li>

<?php }
wp_reset_postdata(); ?>
  </ul>

它有一个小问题。假设我们有 post1 和 post2。它们属于类别 1 和类别 2。如何在显示当前查看的 post1 的相关帖子的单个页面上仅获取 category1 的帖子而不是 cat2 的帖子?

谢谢!

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    只取wp_get_post_categories() 函数返回的第一项

    $cat = wp_get_post_categories($post->ID);
    $related = get_posts( array( 'category__in' => $cat[0], 'numberposts' => 5, 'post__not_in' => array($post->ID) ) );
    

    【讨论】:

    • category__in 接受一个数组,而不是一个字符串。您应该将$cat[0] 转换为数组或使用'cat' =&gt; $cat[0]
    • 这是一个很好的解决方案,但是当帖子属于多个类别时,我遇到了问题。我可以以某种方式从显示中排除一个类别,如果那是某些帖子的 cat[0],那么只在这种情况下使用 cat[1] 吗?我有 id 为 425 的 cat,永远不应该显示 cat,但对于某些帖子,那是 cat[0]。我能以某种方式跳过那只猫吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多