You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码修改WooCommerce中的自定义分类法值

问题:更新WooCommerce自定义分类法值且保留其他分类法

我需要修改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 属性已为产品设置,更新其值
      wp_set_post_terms($products[0] ->ID, $random_number, 'pa_pw', false);
    } else {
      // pa_pw 属性未为产品设置,先添加属性再赋值
      $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;
}

内容的提问来源于stack exchange,提问作者user20947428

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 08:55:37