使用未清理的名称值按名称获取术语

jam*_*pez 5 wordpress themes wordpress-plugin

我想要做的是以编程方式设置woocommerce产品类别.

我有什么是术语名称test & sample和帖子的ID 9,所以设置的产品类别我已经使用get_term_bywp_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');
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我的问题是未经过计算的价值$name.什么是迄今为止我所做的是取代&&哪些工作.

$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
Run Code Online (Sandbox Code Playgroud)

我的问题是如何使用未经过清理的名称值来获取名称或如何清理名称值以正确获取术语ID.

sha*_*sup 2

您可以尝试在将其传递给 之前$name对其进行清理。我相信 WordPress 会将术语、帖子标题、帖子内容等中的特殊 HTML 字符转换为相应的 HTML 实体,以便在渲染页面时这些字符能够正确显示。$name = esc_html( $name );get_term_by()

例子:

$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');
Run Code Online (Sandbox Code Playgroud)