Used to get the most top level category of the current product categories.
The following code must be inserted in the function.php contained in your child theme (**).
Since the action target is ‘wp_head‘, all Echo content will be printed in the header of the page.
/* This code shows the TOP PARENT Category ID of a woocommerce product */
/* It works only for multi-categories products. */
/* The result is printed just after the tag. */
add_action('wp_head', 'get_current_product_parent_category');
function get_current_product_parent_category(){
global $post;
$prod_terms = get_the_terms( $post->ID, 'product_cat' );
if($prod_terms) {
foreach ($prod_terms as $prod_term) {
// gets product cat id
$product_cat_id = $prod_term->term_id;
// gets an array of all parent category levels
$product_parent_categories_all_hierachy = get_ancestors( $product_cat_id, 'product_cat' );
// This cuts the array and extracts the last set in the array
$last_parent_cat = array_slice($product_parent_categories_all_hierachy, -1, 1, true);
foreach($last_parent_cat as $last_parent_cat_value){
// $last_parent_cat_value is the id of the most top level category, can be use whichever one like
$myCat_id=$last_parent_cat_value ;
// eventually print out the ID value
// echo '' . $myCat_id . '';
}
}
if($myCat_id==01){ echo "Please do something !"; }
}
}
(**) How to Create a Child Theme
A child theme is a theme that inherits the functionality and styling of another theme, called the parent theme. Child themes are the recommended way of modifying an existing theme.
- Create child theme directory (common approach to name child theme as the parent theme plus -child added on the end.)
- Create style.css
- Create functions.php
For more detailed instructions on child themes you can visit the following links:
https://developer.wordpress.org/themes/advanced-topics/child-themes/
https://blog.hubspot.com/website/wordpress-create-child-theme