0

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> ';
                }
sb0k
  • 47
  • 1
  • 1
  • 7

1 Answers1

2

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();
diggy
  • 6,748
  • 2
  • 18
  • 24
  • 1
    By the way, to query a random set of posts, you should modify your `$args` a bit: `'order' => 'rand', 'orderby' => 'none'` – diggy Nov 06 '14 at 13:50
  • thank you for the reply, sadly this is not the right solution for me. with your code i get all the posts, like with the wp_get_recent_posts function. when i'm viewing a post, and this post is in the category "Cat-One", i want to show the other post of the same category; and so on with the other posts/categories. – sb0k Nov 07 '14 at 15:55
  • 1
    You can get the category or categories for the current post with `$cats = get_the_terms( get_the_ID(), 'category' ); $cats = wp_list_pluck( $cats, 'term_id' );` and add the following to the query args of get_posts: `'category' => $cats` – diggy Nov 07 '14 at 17:05
  • thank you again. trough your hint i found the solution. – sb0k Nov 07 '14 at 21:49