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

Read More
$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.

Related posts

3 comments

  1. 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');
    
  2. WordPress sanitizes term names through sanitize_term_field (after a chain of functions, it does the real job). Looking the code we can see that name 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 😉

  3. 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');
    }
    

Comments are closed.