TransWikia.com

How to set subcategory in Woocommerce?

WordPress Development Asked by Yves Gonzaga on December 1, 2021

Hello I wanna to ask how can we set a sub category of a post in wordpress programatically?

wp_set_object_terms( $post_id, 'Lense', 'product_cat', false);
wp_set_object_terms( $post_id, 'Canon', 'product_cat', true);

But what it does is not setting the parent and child category it set as both parent category

One Answer

You will have to first insert the term as required using wp_insert_term.

wp_set_object_terms( $post_id, 'Lense', 'product_cat', false); 

This function checks if 'Lense' term exist in product_cat or not. If does not exist, then create and assign. Check whether term already exists or not

$id = term_exists( 'canon','product_cat',$parent_id ) //$parent_id is parent term id, in your case id of Lense
if($id == NULL)
{
    $id = wp_insert_term(
      'Canon', // the term 
      'product_cat', // the taxonomy
      array(
        'description'=> 'Test description',
        'slug' => 'canon',
        'parent'=> $parent_term['term_id']  // get numeric term id of parent - Lense
      )
    
    );
}

wp_set_object_terms( $post_id,$id, 'product_cat',true); 

This will work.
// No space is allowed in taxonomy name

Answered by Aparna_29 on December 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP