Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get term by name using unsanitized name value

What i'm trying to do is to programatically set woocommerce product category.

What I have is the term name test & sample and the post id 9, so to set the products category I have used get_term_by and wp_set_object_terms

$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 unsanitized value of $name. What I have done so far is replace & with & which 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 term by name using unsanitized name value or how to sanitize the name value to get the term id properly.

like image 666
jameshwart lopez Avatar asked Feb 17 '16 22:02

jameshwart lopez


People also ask

How do you get a term name?

You may get the term name from term_id like this: $term_name = get_term( $term_id )->name; Explanation: get_term() returns the term object and name is one of propeties of this object. Save this answer.

How do I get slugs in Wordpress?

You can use $term = get_term_by('id', $id) see get_term_by() codex page. Then access slug using $term->slug .


1 Answers

You could try cleansing the $name with $name = esc_html( $name ); before passing it to get_term_by(). I believe wordpress converts special HTML characters in terms, post titles, post contents, etc to their corresponding HTML entities so that the characters show up properly when the page is rendered.

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');
like image 67
shamsup Avatar answered Sep 23 '22 11:09

shamsup