是否可以显示与当前帖子相同类别的相关帖子? [英] Is it possible to display related posts from same category as the current post?

查看:23
本文介绍了是否可以显示与当前帖子相同类别的相关帖子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了有关此主题的其他帖子,但对我没有帮助.如果我将此代码添加到我的代码中,是否可以显示与当前帖子相同类别的相关帖子?

I found other post on this topic but it did not help me. If I add this code to my code, is it possible to display related posts from same category as the current post?

我发布下面的代码来展示我想要实现的目标:

I'm posting the code below to show what I'm trying to achieve:

<?php
$related = get_posts( array( 'category__in' => 
wp_get_post_categories($post->ID), 'numberposts' => 5, 'post__not_in' => array($post->ID) ) );
if( $related ) 
    foreach( $related as $post ) {
        setup_postdata($post); ?>
        <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
    <?php }

    wp_reset_postdata(); ?>

推荐答案

显示同类别的相关帖子

$terms = get_the_terms( $post->ID, 'category' );

        if ( empty( $terms ) ) $terms = array();

        $term_list = wp_list_pluck( $terms, 'slug' );

        $related_args = array(
            'post_type' => 'post',
            'posts_per_page' => 5,
            'post_status' => 'publish',
            'post__not_in' => array( $post->ID ),
            'orderby' => 'rand',
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'slug',
                    'terms' => $term_list
                )
            )
        );

        $my_query = new WP_Query($related_args);

        if( $my_query->have_posts() ) {
        while ($my_query->have_posts()) : $my_query->the_post();

        the_title();
        echo "<br>";

        endwhile;
        }
    wp_reset_query();

这篇关于是否可以显示与当前帖子相同类别的相关帖子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆