• sb0k

    (@sb0k)


    HI,
    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 :

    $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

Viewing 2 replies - 1 through 2 (of 2 total)
  • Safeer

    (@safeerz)

    Please try this

    $args = array(
    	'post_type' => 'product',
    	'category__in' => wp_get_post_categories($post->ID),
    	'numberposts' => 4,
    	'post__not_in' => array($post->ID)
    	);
    
    $related = get_posts( $args );
    if( $related ) foreach( $related as $post ) {
    setup_postdata($post); ?>
     <div class="col-md-3">
            <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
                <?php the_content('Read the rest of this entry &raquo;'); ?>
            </div>
    <?php }
    wp_reset_postdata();

    Let me know if it works

    Thread Starter sb0k

    (@sb0k)

    Hi safeer, thank you so much for your reply.

    I just solved my problem with this code :

    $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> ';
                    }

    i don’t know exactly if it’s right but works.

    i just tried your code and it works perfectly too.

    thank you again

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘add related posts to single page’ is closed to new replies.