Search code examples
phpwordpresswoocommercehookcategories

Woocommerce create_product_cat hook has no thumbnail_id / image information attached for product categories


I have written code to hook into the creation of a category on Woocommerce. This code gets me all of the information except the "displayType" and "thumbnail_id". When hooking into the 'edited_product_cat' these fields are present.

My question is if there is a way/code to get the thumbnail_id on creation as well, or if there is a different hook that makes this possible?

Current code looks like the following:

function loader() {
        add_action('create_product_cat', [$this, 'onCategoryCreated'], 10, 2);
        add_action('edited_product_cat', [$this, 'onCategoryCreated'], 10, 2);
}

function onCategoryCreated ($categoryId){
        $cat = get_term_by( 'id', $categoryId, 'product_cat', 'ARRAY_A' );
        $catMeta = get_term_meta( $cat["term_id"] );
        $thumbnailId = get_term_meta( $cat["term_id"], 'thumbnail_id', true );
        $imageUrl = wp_get_attachment_url( $thumbnailId );

        error_log(json_encode($cat));
        error_log(json_encode($catMeta));
        error_log($thumbnailId);
        error_log($imageUrl);
}

which prints out the following for a create:

-> {"term_id":52,"name":"create","slug":"create","term_group":0,"term_taxonomy_id":52,"taxonomy":"product_cat","description":"create desc","parent":0,"count":0,"filter":"raw"} 
-> {"order":["0"]}
-> 
-> 

and the following for update:

-> {"term_id":35,"name":"update","slug":"update","term_group":0,"term_taxonomy_id":35,"taxonomy":"product_cat","description":"update desc","parent":0,"count":0,"filter":"raw"}
-> {"order":["0"],"display_type":[""],"thumbnail_id":["7"]}
-> 7
-> http://localhost:8888/myWebsite/wp-content/uploads/2021/11/6ac25e82-9d4c-3f59-ad83-a06f7966a0fd.jpg

Solution

  • Use created_product_cat instead of create_product_cat

    function loader() {
            add_action('created_product_cat', [$this, 'onCategoryCreated'], 10, 2);
            add_action('edited_product_cat', [$this, 'onCategoryCreated'], 10, 2);
    }
    
    function onCategoryCreated ($categoryId){
            $cat = get_term_by( 'id', $categoryId, 'product_cat', 'ARRAY_A' );
            $catMeta = get_term_meta( $cat["term_id"] );
            $thumbnailId = get_term_meta( $cat["term_id"], 'thumbnail_id', true );
            $imageUrl = wp_get_attachment_url( $thumbnailId );
    
            error_log(json_encode($cat));
            error_log(json_encode($catMeta));
            error_log($thumbnailId);
            error_log($imageUrl);
    }