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.
You could try cleansing the
$name
with$name = esc_html( $name );
before passing it toget_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:
WordPress sanitizes term names through
sanitize_term_field
(after a chain of functions, it does the real job). Looking the code we can see thatname
passes through two filters:'edit_term_name'
and'edit_category_name'
(lines 1880 and 1893). It seems that wordpress doen’t plug any functions to those filters, so the only transformation occurs at line 1898;$value = esc_attr($value);
That said you can use
$name = esc_attr('test & sample');
and that should do the trick 😉Try the following: