Dennis
Dennis

Reputation: 538

Custom post type - related products

I've made a custom post type "product" on my Wordpress site. The detail page of a product is single-product.php which shows everything about the product perfectly.

All the product will be categorized in the following structure:

  1. Toegangscontroles

    1. Elektronische sloten
    2. Wandlezers
    3. Software
    4. ...
  2. Overige producten

    1. Sleutelkaarten
    2. Kluizen
    3. ...

I have two test products on my website. Both products have the category "Electronische sloten". Which is a child category of "Toegangscontroles".

Category

I want to show related products on single-product.php This related product cannot be the current product itself and must be under the same parent category. So in this case, a product with child category "Toegangscontroles" must show 5 random related products from the child categories from parent "Toegangscontroles".

This is my code now:

<?php
    $related = get_posts( array( 
        'post_type' => 'product',
        '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(); ?>"><?php the_title(); ?></a>

    <?php }
    wp_reset_postdata();    
 ?>

When I go the product A, I see product B under related products, but when I go the the product B page, I don't see product A. Tough they have exactly the same category.

Thanks in advance.

Upvotes: 0

Views: 1362

Answers (2)

Vitali Protosovitski
Vitali Protosovitski

Reputation: 583

Haven't tested this, but you can try

$related = get_posts( array( 
  'post_type' => 'product',
  'tax_query' => array( array(
    'taxonomy' => $taxonomy_name,
    'field' => 'term_id',
    'terms' => wp_get_post_terms($post->ID, $taxonomy_name, array('fields' => 'ids'))        
  ) ),
  'numberposts' => 5, 
  'exclude' => array($post->ID)
) );

Upvotes: 1

raju_odi
raju_odi

Reputation: 1475

Please use below code i think it will work.

$related = new WP_Query(
    array(
        'category__in'   => wp_get_post_categories( $post->ID ),
        'posts_per_page' => 5,
        'post__not_in'   => array( $post->ID )
    )
);

if( $related->have_posts() ) { 
    while( $related->have_posts() ) { 
        $related->the_post(); ?>
       <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php }
    wp_reset_postdata();
} ?>

Upvotes: 0

Related Questions