首页 > 解决方案 > 从 Woocommerce 产品中删除未在产品变体中使用的额外属性

问题描述

实际上,我有一个 Woocommerce 网站,其中包含大约 800 种产品。许多产品是可变产品,每个产品都有一些属性,用作变体,但问题是许多产品分配了未使用的属性,这些属性没有用于特定的产品变体。

所以我想从每个产品中删除未使用的属性,这些属性未用于该特定产品的变体。

寻找对我有帮助的查询或一些代码片段,而不是检查每个产品。

现在,我不知道该怎么做。

我只想删除未在该产品变体中使用的未使用属性。

标签: wordpresswoocommerce

解决方案


尝试运行此脚本:https ://gist.github.com/yratof/f21242d4263c461f4a5b6b766cd24373

add_action( 'init', function() {
  ini_set( 'memory_limit', '2048M' );
  set_time_limit( 0 );
  $posts = get_posts( [
    'post_type' => 'product',
    'posts_per_page' => -1
  ] );
  $count = 0;
  foreach ( $posts as $post ) {
    $product = get_product( $post );
    if ( $product->product_type !== 'variable' ) {
      continue;
    }
    $count ++;
    $va = $product->get_variation_attributes();
    $vas = [];
    foreach ( $product->get_attributes() as $attribute ) {
      if ( isset( $attribute['is_taxonomy'] ) && $attribute['is_taxonomy'] ) {
        $terms = wp_get_post_terms( $product->id, $attribute['name'] ) ;
        // var_dump( $terms );
        foreach ( $terms as $term ) {
          if ( in_array( $term->slug, $va[ $attribute['name'] ] ) ) {
            // var_dump( $term );
            if ( ! isset( $vas[$attribute['name']] ) ) {
              $vas[$attribute['name']] = [];
            }
            $vas[$attribute['name']][] = $term->term_id;
          }
        }
      }
    }
    foreach ($vas as $tax => $vals) {
      wp_set_post_terms(  $product->id, $vals, $tax  );
    }
  }
  wp_die( 'All attributes have been filtered: Total products changed: '. $count );
} );

推荐阅读