Is it possible to display related posts from same

2019-06-09 21:48发布

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(); ?>

标签: wordpress
1条回答
SAY GOODBYE
2楼-- · 2019-06-09 22:13

Display related posts from the same category

$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();
查看更多
登录 后发表回答