What I'm trying to do is programmatically set the woocommerce product category.
I have the term name test & sample and post id 9 , so I used get_term_by and wp_set_object_terms to set the product category
$name = 'test & sample'; $posid = 9; //get the term based on name $term = get_term_by('name', $name, 'product_cat'); //set woocommerce product category wp_set_object_terms($posid, $term->term_id, 'product_cat');
As you can see, my problem is the unmanned value of $name . What I have done so far is to replace & with & that work.
$name = str_replace('&', '&', 'test & sample'); $posid = 9; //get the term based on name $term = get_term_by('name', $name, 'product_cat'); //if term does exist,then use set object terms if(false != $term){ //set woocommerce product category wp_set_object_terms($posid, $term->term_id, 'product_cat'); } //if the term name doe not exist I will do nothing
My question is: how to get a term by name using the value of the unanitated name, or how to sanitize the value of the name in order to get the term identifier correctly.
source share