Reputation: 35
I want to update a value to a specific custom field in all Woocommerce products at once. But this is not working
function update_products_by_x(){
$products_ids = get_posts( array(
'post_type' => 'product', // or ['product','product_variation'],
'post_status' => 'publish',
'fields' => 'ids'
) );
foreach ( $products_ids as $product_id ) {
$product = wc_get_product($product_id);
update_post_meta($product_id, 'field_name_here', esc_attr('field_value_here'));
}
}
add_action('wp_footer', 'update_products_by_x');
Upvotes: 0
Views: 442
Reputation: 1661
Use WP_Query
to retrieve all products and hook your function to init
:
add_action('init', 'update_products_by_x');
function update_products_by_x(){
if(isset($_GET['update_woo_products'])){
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
update_post_meta($product->ID, 'field_name_here', esc_attr('field_value_here'));
endwhile;
wp_reset_query();
die('done');
}
}
If you notice there is a small condition to make sure that this only run if requested, so to run this function you'd need to visit the website and make sure you add the parameter update_woo_products
as a query string (eg: https://example.com/?update_woo_products=1 )
This will run the function and show a white page with the message done
, which means that the condition was met and the function was executed successfully.
Upvotes: 1