How to show product parent category in woocommerce?

by darrion.kuhn , in category: PHP CMS , 7 months ago

How to show product parent category in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 7 months ago

@darrion.kuhn 

To show the product parent category in WooCommerce, you can use the following code snippet in your theme's functions.php file or in a custom plugin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function display_product_parent_category() {
    global $product;

    $categories = get_the_terms( $product->get_id(), 'product_cat' );

    if ( $categories && ! is_wp_error( $categories ) ) {
        $parent_categories = array();

        foreach ( $categories as $category ) {
            if ( $category->parent == 0 ) {
                $parent_categories[] = $category;
            }
        }

        if ( ! empty( $parent_categories ) ) {
            echo '<p>Parent Category: ' . $parent_categories[0]->name . '</p>';
        }
    }
}

add_action( 'woocommerce_single_product_summary', 'display_product_parent_category', 5 );


This code snippet will display the parent category of the product on the single product page in WooCommerce. You can customize the code further to display the parent categories in a different format or location on the product page.