Retrieve a term by name using the value of an unanitled name

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.

+5
source share
3 answers

You can try to clear $name with $name = esc_html( $name ); before passing it to get_term_by() . I believe Wordpress converts HTML special characters in terms, message headers, messages, etc. Into their corresponding HTML entities so that the characters display correctly when rendering the page.

Example:

 $name = esc_html('test & sample'); // cleanses to 'test & sample' $posid = 9; $term = get_term_by('name', $name, 'product_cat'); wp_set_object_terms($posid, $term->term_id, 'product_cat'); 
+2
source

Wordpress sanitize_term_field term names through sanitize_term_field (after a chain of functions, it does the real work). Looking at the code , we see that name goes through two filters: 'edit_term_name' and 'edit_category_name' (lines 1880 and 1893). Wordpress doesn't seem to connect any functions to these filters, so the only conversion happens on line 1898; $value = esc_attr($value);

Having said that you can use $name = esc_attr('test & sample'); and this should do the trick;)

+2
source

Try the following:

 $name = 'test & sample'; $postid = 9; $term = get_term_by('name', apply_filters( 'pre_term_name', $name, 'product_cat'), 'product_cat'); if (is_object($term)) { wp_set_object_terms($postid, $term->term_id, 'product_cat'); } 
+1
source

Source: https://habr.com/ru/post/1243267/


All Articles