【问题标题】:Add attributes to WooCommerce product with PHP使用 PHP 向 WooCommerce 产品添加属性
【发布时间】:2019-06-02 07:13:06
【问题描述】:

我正在尝试向现有 WooCommerce 产品添加具有多个值的新属性。

这是我正在使用的代码。我把它简化了一点,让它更清楚。

$productId = 87356;

$attr = get_post_meta( $productId, '_product_attributes', true );

$gears = [ '3', '7' ];

$attr['pa_aantal-versnellingen'] = [
    'name' => 'pa_aantal-versnellingen',
    'value' => implode(' | ', $gears),
    'is_visible' => '1',
    'is_variation' => '1',
    'is_taxonomy' => '1'
];

update_post_meta( $productId, '_product_attributes', $attr );

foreach ( $gears as $gear ) {
    wp_set_object_terms( $productId, $gear, 'pa_aantal-versnellingen', true );
}

该属性出现在产品的属性列表中。但是没有添加条款。

这些术语也确实存在于数据库中:

我做错了什么?我做了很多研究,阅读了一些其他问题,但它们对我没有帮助。

Create new product attribute programmatically in Woocommerce

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    在研究了WordPress ERD 之后,我想出了一个解决方法。

    我使用普通的 MySQL 查询而不是 wp_set_object_terms();

    1. wp_term_taxonomy 表中获取term_taxonomy_id

      $placeholders = array_fill( 0, count( $gears ), '%s' );
      $format = implode( ', ', $placeholders );
      
      $sql = 
          "SELECT tt.term_taxonomy_id" .
          "FROM {$wpdb->prefix}term_taxonomy tt" .
          "JOIN {$wpdb->prefix}terms t ON tt.term_id = t.term_id" . 
          "WHERE tt.taxonomy = 'pa_aantal-versnellingen' AND t.name IN($format)"
      ;
      
      $termTaxIds = $wpdb->get_results( $wpdb->prepare( $sql, $gears ), ARRAY_N );
      
    2. 对于每个term_taxonomy_id 值,在wp_term_relationships 表中插入一个新条目

      foreach ( $termTaxIds as $termTaxId ) {
          $insertSql = 
              "INSERT INTO {$wpdb->prefix}term_relationships" .
              "(object_id, term_taxonomy_id, term_order)" .
              "VALUES (%d, %d, 0)"
          ;
      
          $wpdb->query( $wpdb->prepare( $$insertSql, $productId, $termTaxId[0] ) );
      }
      

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 2014-06-20
      • 2022-12-17
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多