0

I'm trying to get the current category name/slug of a product.

let me explain, I have a product that is in 3 Different categories like this: Beds(Main Category)->Firm Bed(Sub Category)->Single Bed(Sub Sub Category). Currently, woocommerce will get related products from all 3 Categories. But I would like to get only from the Category the product is in like Single Bed.

Now I have tried the following: Woocommerce: Get current product category and how to get current product category name in woocommerce

the following website also helped. https://njengah.com/get-current-product-category/

by current code looks like this:

    add_action('wp_head', 'get_current_product_category');

function get_current_product_category(){
global $post;
if ( is_single() && 'product' === get_post_type( $post ) ) {
        $product_categories = wp_get_post_terms( $post->ID, 'product_cat' );

        if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
            foreach ( $product_categories as $category ) {
                echo 'Category ID: ' . $category->term_id . '<br>';
                echo 'Category Name: ' . $category->name . '<br>';
            }
        }
    }

}

this works but brings up all the categories and nut the last once the product is for example Single beds.

using the latest woocommerce and WordPress versions.

1 Answers1

0

Try using this woocommerce_related_products hook and you can remove the parent category from sub category.

function custom_related_products_query( $args ) {
    global $post, $product;

    // Get the product categories for the current product
    $product_categories = wp_get_post_terms( $post->ID, 'product_cat', array( 'fields' => 'ids' ) );

    // Get only the sub-categories (sub-sub-categories) of the current product
    $sub_categories = array();
    foreach ( $product_categories as $category_id ) {
        $category = get_term( $category_id, 'product_cat' );
        if ( $category->parent != 0 ) {
            $sub_categories[] = $category_id;
        }
    }

    // Include only products from the sub-categories
    $args['product_cat'] = $sub_categories;

    return $args;
}
add_filter( 'woocommerce_related_products', 'custom_related_products_query' );

Hope this helps!

Muhammad Ahmad
  • 191
  • 1
  • 7