skip to Main Content

I have a question regarding the product category. I have a category like that:

-electronic
-- laptop
-- mobile

then I want to create a logic for all product under electronic, I use is_product_category( ‘electronic’ ), but it doesn’t work for electronic, it only works when URL is mywebsite.com/product-category/electronic when I use mywebsite.com/product-category/electronic/mobile/ it doesn’t work. Should I use the following codes or there is another option:

is_product_category( ‘laptop’ )
is_product_category( ‘mobile’ )

2

Answers


  1. You can use term_is_ancestor_of() to check if the current term (product category) being viewed belongs to a parent term.

    I’ve written a simple helper function:

    /**
     * @param int|object $parent ID or object term object to check.
     * @return bool Whether the product category being viewed is a child of the given parent category.
     */
    function wpse_is_child_product_category( $parent ) {
        if ( ! is_product_category() ) {
            return false;
        }
    
        return term_is_ancestor_of( $parent, get_queried_object(), 'product_category' );
    }
    

    Usage:

    if ( is_product_category( 5 ) || wpse_is_child_product_category( 5 ) ) {
        // . . .
    
    Login or Signup to reply.
  2. You can create a custom conditional function that handle also any children product category on product category archives like (handle term name, term slug or term id):

    /**
     * Determines whether the query is for an existing product category archive page or for an ancestors product category archive page.
     *
     * @param int|string term ID, term slug or term name to check.
     * @return bool
     */
    function is_maybe_child_product_category( $category ){
        if( is_product_category( $category ) ) {
            return true;
        }
    
        $object = get_queried_object();
    
        if( ! is_a( $object, 'WP_Term') ) {
            return false;
        }
    
        $taxonomy = $object->taxonomy;
        $children = get_term_children( $object->term_id, $taxonomy );
        $result   = (array) term_exists( $category, $taxonomy );
    
        if( ! empty( $result ) ) {
            return false;
        }
        return in_array( reset($result), $children );
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    USAGE:

    if ( is_maybe_child_product_category( 'laptop' ) ) {
        // Do something
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search