categories - Show the parent taxonomy by creating shortcode in woocommerce?

admin2025-01-07  5

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.

Share Improve this question edited May 25, 2020 at 2:33 lewishole asked May 22, 2020 at 4:53 lewisholelewishole 1011 bronze badge 2
  • do you mean automatically add the shortcode? – gael Commented May 22, 2020 at 7:34
  • no gael, I want to manually type the shortcode on "Healthy Fruits" product archive page – lewishole Commented May 22, 2020 at 8:15
Add a comment  | 

2 Answers 2

Reset to default 0

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/

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736264863a1000.html

最新回复(0)