简体   繁体   中英

Wordpress set product category by name and parent category

I need to set product category by name

but i have two different sub-category with same name but different parent cat

I use :

wp_set_object_terms($post_id, $my_categories, 'product_cat');

but in this way wordpress set the sub-cat with low id not the right sub-cat for relative parent cat

eg. : T-shirt (parent category is Woman) and T-shirt (parent category is Man)

How can I set the right sub-category to the product?

You can set category list from your parent category ID.

Please check below code:

$args = array('parent' => 17); // Here pass your parent category ID(Man or Female)
$categories = get_categories( $args );
foreach($categories as $category) { 
    echo '<p>Category: <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a> </p> ';
    echo '<p> Description:'. $category->description . '</p>';
    echo '<p> Post Count: '. $category->count . '</p>';  
}

In this way, You will get all the category name with other details from parent one.

This way you can display T-shirt category from different male and female category.

Hope this will helpful for you. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM