从Woocommerce产品中删除未在产品版本中使用的额外属性

问题描述 投票:0回答:1

实际上,我有一个Woocommerce网站,有大约800个产品。并且许多产品是可变产品,并且每个产品都具有一些属性,这些属性用作变体,但问题是许多产品已经分配了未使用的属性,这些属性未在特定产品变体中使用。

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

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

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

我只想删除未使用的属性,这些属性未在该产品版本中使用。

wordpress woocommerce
1个回答
0
投票

尝试运行此脚本: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 );
} );
© www.soinside.com 2019 - 2024. All rights reserved.