【问题标题】:Remove extra attributes from Woocommerce products which are not used in product variations从 Woocommerce 产品中删除未在产品变体中使用的额外属性
【发布时间】:2023-03-11 00:40:01
【问题描述】:

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

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

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

目前,我不知道该怎么做。

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

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    尝试运行此脚本: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 );
    } );
    

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 2019-02-12
      • 2023-03-14
      • 2018-10-11
      相关资源
      最近更新 更多