phpwordpressrelated-content

add related posts to single post wordpress template


i'm trying to show a module with the related products in a single post page.

I created a cpt called "Product", and a taxonomy called "category".

What i want to do is to show, in the single post page, the other products of the same category.

Until now i successfully add the other posts with the function wp_get_recent_post, but of course i get all posts.

how i can pass the class to query ?

this is my code :

<?php
$args = array(
            'numberposts' => '4',
            'orderby' => 'rand',
            'post_type' => 'product',
            'post_status' => 'publish'
             );
            $recent_posts = wp_get_recent_posts( $args );
            foreach( $recent_posts as $recent ){
                echo '<div class="col-md-3"><a href="' . get_permalink($recent["ID"]) . '">'. get_the_post_thumbnail($recent["ID"], 'thumbnail' ) . $recent["post_title"].'</a> </div> ';
            }
?>

thank you

Edit.

i solved this way:

            $terms = get_the_terms( $post->ID , 'category' );
                if ( $terms != null ){
                foreach( $terms as $term );
                }

            $args = array(
            'post_type' => 'product',
            'post__not_in' => array($post->ID),
            'tax_query' => array(
                array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $term->slug))
                );

            $recent_posts = wp_get_recent_posts( $args );
            foreach( $recent_posts as $recent ){
                echo '<div class="col-md-3"><a href="' . get_permalink($recent["ID"]) . '">'. get_the_post_thumbnail($recent["ID"], 'thumbnail' ) . $recent["post_title"].'</a> </div> ';
                }

Solution

  • Use get_posts() (codex):

    $related = get_posts( $args );
    foreach( $related as $post ){
        setup_postdata( $post );
        echo '<div class="col-md-3"><a href="' . get_permalink() . '">'. get_the_post_thumbnail( get_the_ID(), 'thumbnail' ) . get_the_title() . '</a></div>';
    }
    wp_reset_postdata();