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.