我需要一个简单的功能,允许我添加或替换空 sku 代码,以使用产品的父 sku 在我的已发布产品中进行变体。
有没有办法获得这项工作?
我需要一个简单的功能,允许我添加或替换空 sku 代码,以使用产品的父 sku 在我的已发布产品中进行变体。
有没有办法获得这项工作?
更新:要将已发布产品中的空 SKU 代码替换为父 SKU (可变产品 SKU),请尝试仅适用于管理员用户角色的此功能。
在运行之前做一个数据库备份
要运行此功能,请浏览您的商店页面:
当所有变体 SKU 都将更新时,会显示一条消息让您知道工作已完成。
编码:
add_action('woocommerce_before_main_content', 'update_variations_sku', 100 );
function update_variations_sku(){
global $wpdb;
$results = $results2 = array();
$limit = 2500; // Number of variations to process
// The SQL query (get the variations with empty sku and their parent product ID)
$query = $wpdb->get_results( "
SELECT p.ID, p.post_parent
FROM {$wpdb->prefix}posts as p
INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type LIKE 'product_variation'
AND p.post_status LIKE 'publish'
AND pm.meta_key LIKE '_sku'
LIMIT $limit
" );
if( count($query) == 0 ){
echo "<p><pre>The job is finished, you can remove the code</pre></p>";
return; // exit
}
// Loop through variation Ids and get the parent variable product ID
foreach( $query as $value )
$results[$value->post_parent][] = $value->ID;
// Loop through variation Ids and set the parent sku in related empty variations skus
foreach($results as $parent_id => $variation_ids){
$parent_sku = get_post_meta( $parent_id, '_sku', true );
$count = 0;
foreach($variation_ids as $variation_id){
$count++;
update_post_meta( $variation_id, '_sku', $parent_sku.'-'.$count );
}
}
if( count($query) < $limit ){
echo "<p><pre>The job is finished, you can remove the code <br>$count variations SKUs have been updated</pre></p>";
} else {
echo "<p><pre>$count variations SKUs have been updated (continue reloading the page again)</pre></p>";
}
}
代码进入活动子主题(或主题)的 function.php 文件中。
测试和工作。