Reputation: 83
I'm trying to update a custom field in WooCommerce under each variation within all products. I got the code to work for a simple product, but cannot loop through the variations and update them. I tried nearly every WooCommerce variations loop on Stackoverflow but all of them return errors or simply don't work. Any suggestions would be really appreciated. Current code in functions.php for simple products.
add_action('init', 'bulk_update_post_meta_data');
function bulk_update_post_meta_data() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'suppress_filters' => true
);
$posts_array = get_posts( $args );
foreach($posts_array as $post_array) {
$Cogcost = get_post_meta( $post_array->ID, '_regular_price', true );
update_post_meta($post_array->ID, '_wc_cog_cost', $Cogcost);
}
}
Upvotes: 1
Views: 2145
Reputation: 11861
add_action( 'init', 'bulk_update_post_meta_data' );
function bulk_update_post_meta_data() {
$args = array(
'posts_per_page' => -1,
'post_type' => 'product_variation',
'suppress_filters' => true
);
$posts_array = get_posts( $args );
foreach ( $posts_array as $post_array ) {
$Cogcost = get_post_meta( $post_array->ID, '_regular_price', true );
update_post_meta( $post_array->ID, '_wc_cog_cost', $Cogcost );
}
}
This will get all variations.
Upvotes: 1