wordpress - 从 Woocommerce 产品中删除未在产品变体中使用的额外属性
问题描述
实际上,我有一个 Woocommerce 网站,其中包含大约 800 种产品。许多产品是可变产品,每个产品都有一些属性,用作变体,但问题是许多产品分配了未使用的属性,这些属性没有用于特定的产品变体。
所以我想从每个产品中删除未使用的属性,这些属性未用于该特定产品的变体。
寻找对我有帮助的查询或一些代码片段,而不是检查每个产品。
现在,我不知道该怎么做。
我只想删除未在该产品变体中使用的未使用属性。
解决方案
尝试运行此脚本: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 );
} );
推荐阅读
- javascript - 为什么我在哨兵中收到用户反馈的空白响应?
- javascript - 如何通过 JavaScript 中的人员 API 创建联系人?
- java - 使用非标准 Maven 存储库位置进行 gradle 构建
- javascript - 如何使excel将字符串放入新行
- django - Docker-Compose + Django + PostgreSQL + uwsgi + Nginx 找不到 404
- java - 使用其他方法的对象实例
- android - android - webview 网站无法正常工作
- typescript - TypeScript 参数类型推断失败
- python - Python Selenium 脚本基于远程网页 url 生成屏幕截图 - 显示 Twitter 提要/左侧栏图像的一些随机图像图标部分
- angular - Angular项目中带或不带export关键字的类和接口