Reputation: 538
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:
Toegangscontroles
Overige producten
I have two test products on my website. Both products have the category "Electronische sloten". Which is a child category of "Toegangscontroles".
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
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
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