How would I create a shortcode to show the parent taxonomy in woocommerce?
My product categories should be like:
- Food
-- Fruits
--- Healthy Fruits
--- Organic Fruits
-- Meat
--- Pork
--- Lamb
--- Beef
For example, I would like to display the taxonomy name "Fruits" in somewhere when user at the "Healthy Fruits" product archive page.
How would I create a shortcode to show the parent taxonomy in woocommerce?
My product categories should be like:
- Food
-- Fruits
--- Healthy Fruits
--- Organic Fruits
-- Meat
--- Pork
--- Lamb
--- Beef
For example, I would like to display the taxonomy name "Fruits" in somewhere when user at the "Healthy Fruits" product archive page.
The Shortcode to display products in "Fruits" category when user is on another page or archive... is:
[products category="fruits"]
As far as I know there is no shortcode to display the parent category products without specifying the given category slug.
For your 2nd example you will have to call it in your sub category "Pork"
[products category="meat"]
and so on for each category.
You can find WooCommerce shortcodes here:
https://docs.woocommerce.com/document/woocommerce-shortcodes/
Here is shortcode function that will display parent category
// Register the shortcode
function display_parent_taxonomy_shortcode() {
add_shortcode('parent_taxonomy', 'get_parent_taxonomy');
}
add_action('init', 'display_parent_taxonomy_shortcode');
// Callback function for the shortcode
function get_parent_taxonomy() {
// Check if we are on a product category archive page
if (is_product_category()) {
global $wp_query;
// Get the current category object
$category = $wp_query->get_queried_object();
// Get the parent category ID
$parent_id = $category->parent;
// If the parent ID is greater than 0, get the parent category
if ($parent_id > 0) {
$parent_category = get_term($parent_id, 'product_cat');
$parent_name = $parent_category->name;
// Return the parent category name
return $parent_name;
}
}
// If not on a product category archive page or parent category not found, return an empty string
return '';
}
Now insert the [parent_taxonomy] shortcode in your desired location
Reference: https://techvila.com/shortcode-to-show-the-parent-taxonomy-in-woocommerce/