We need to update about 15.000 products with a meta_option after a plugin gets activated or after a plugin gets installed.
However, our code does not execute on all products, though the plugin activates fine.
function on_activate_function()
{
// set all products to csa_stock true
// getting all products
$products_ids = get_posts(array(
'post_type' => 'product', // or ['product','product_variation'],
'post_status' => 'publish',
'fields' => 'ids',
'meta_query' => array(array(
'key' => '_stock_from_csa',
'compare' => 'NOT EXISTS',
))
));
// Loop through product Ids
foreach ($products_ids as $product_id) {
// Get the WC_Product object
$product = wc_get_product($product_id);
// Mark product as updated
$product->update_meta_data('_stock_from_csa', true);
$product->save();
}
}
register_activation_hook(__FILE__, 'on_activate_function');
We are using the hook register_activation_hook
to execute code on the activation of the plugin.
The idea was to get all post ids based on a meta_query and then loop over the product ids, get each product associated with the id and then update the meta_data.
Considering the large amount of products this might not be the best approach, as in: doing this operation without batches and in a single run.
Is there a better way to update all products? Can it be done directly via SQL instead of doing this in PHP?
post_per_page => -1
to return all posts or process in batches docs.wpvip.com/how-tos/write-custom-wp-cli-commands/…