2
votes

It is about WooCommerce single product pages. I'm trying to use the product category to display the related products. I'm able to display it with the code below. Using this will include the current post and it displays the product only.

<?php
    global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );     
        foreach ($terms  as $term  ) {         
            $product_cat_name = $term->name;
            break;
        }           
    $ids = array(); 

    $currentID = get_the_ID();

    $args = array('post_type' => 'product', 'product_cat' => $product_cat_name);    
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); global $product; 
        $ids[] = $loop->post->ID; 
    endwhile;
    wp_reset_query();   

    print_r($ids);
?>

But I'm trying to prevent the current product to be displayed on that related products. I have tried to use the first second of the code below, but instead of excluding, it retrieves all the default posts.

<?php
    global $post;
        $terms = get_the_terms( $post->ID, 'product_cat' );     
        foreach ($terms  as $term  ) {         
            $product_cat_name = $term->name;
            break;
        }           
    $ids = array();    

    $currentID = get_the_ID();

    $args = array('post_type' => 'product', 'product_cat' => $product_cat_name, 'post__not_in' => array($currentID));    
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post(); global $product; 
        $ids[] = $loop->post->ID; 
    endwhile;
    wp_reset_query();   

    print_r($ids);
?>

How can I achieve this?

Thanks

1
Ok I have a functional answer for you… it should work. I have removed in my code global $product; as unneeded here. Please try it and tell me.LoicTheAztec

1 Answers

2
votes

Based on your first code snippet, this should work and will avoid to display your current product in the related products based on the current product category.

This is the code:

<?php

global $post;

$ids = array();

// Get the "main" product category 
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ){
    if($term->parent != 0) {
        $product_cat_name = $term->name;
        break; // stop the loop
    }
// The Query    
$loop = new WP_Query( array(
    'post_type' => 'product',
    'product_cat' => $product_cat_name,
    'post__not_in' => array($post->ID) // Avoid displaying current product
) );

if ( $loop->have_posts() ): 
    while ( $loop->have_posts() ) : $loop->the_post();
        $ids[] = $loop->post->ID; // Set all other product IDs for that product category
    endwhile;
endif;

wp_reset_query();

// Raw output
print_r($ids);

?>

This should work…