我想更改woocommerce中自定义分类的值。
function get_pw_by_email($email) {
$products = get_posts(array('post_type' =>'product', 'tax_query' =>array(array('taxonomy' =>'pa_e-mail', 'field' =>'name', 'terms' =>$email))));
$terms = wp_get_post_terms($products[0] ->ID, 'pa_pw', true);
if (empty($terms)) {
return '';
}
return $terms[0]->name;
}
这样我就可以得到正确的分类值。但是现在我想创建一个随机数并更新该值-而不丢失该产品的所有其他分类。
更新:我能够解决它。
function get_pw_by_email($email) {
$products = get_posts(array('post_type' =>'product', 'tax_query' =>array(array('taxonomy' =>'pa_e-mail', 'field' =>'name', 'terms' =>$email))));
if (empty($products)) {
return '';
}
$random_number = rand(10000000, 99999999);
$attributes = get_post_meta($products[0] ->ID, '_product_attributes', true);
$terms = wp_get_post_terms($products[0]->ID, 'pa_pw', true);
if (isset($terms[0]->name)) {
// pa_pw attribute is already set for the product, set its value
wp_set_post_terms($products[0] ->ID, $random_number, 'pa_pw', false);
} else {
// pa_pw attribute is not set for the product, add it and set its value
$attributes['pa_pw'] = array('name' => 'pa_pw','value' => null,'is_visible' => '0','is_taxonomy' => '1',);
update_post_meta($products[0] ->ID, '_product_attributes', $attributes);
wp_set_post_terms($products[0] ->ID, $random_number, 'pa_pw', false);
}
$terms = wp_get_post_terms($products[0]->ID, 'pa_pw', true);
if (empty($terms)) {
return '';
}
return $terms[0]->name;
}
1条答案
按热度按时间xxhby3vn1#
如果您是在每个产品的基础上执行此操作,并且不修改全局分类法,那么一个选项可以是获取要替换的术语(就像您现在所做的那样),使用wp_remove_object_terms()删除它,然后使用wp_set_post_terms()附加新的、修改过的术语。