I have the following working code, which gets all products whose custom date field is today (in UK date format, thanks to the solution offered here) and updates the same field to yesterday. Although this works perfectly, it does not trigger either the woocommerce_update_product or woocommerce_process_product_meta hook, which is required by another plugin to refresh the product cache.
$args = array(
'post_type' => 'product',
'posts_per_page' => 500,
'meta_query' => array(
array(
'key' => '_custom_date',
'value' => date("d/m/Y"), // Convert current date to d/m/Y format
'compare' => '=',
'type' => 'CHAR', // Because _custom_date is stored as a string
),
),
'orderby' => 'meta_value',
'order' => 'ASC',
);
$yesterday = date('d/m/Y',strtotime("-1 days"));;
$loop = new WP_Query( $args );
if ( $loop->have_posts() ): while ( $loop->have_posts() ): $loop->the_post();
global $product;
$product_id = $product->get_id();
$product_date = $product->get_meta('_custom_date');
update_post_meta($product_id, '_custom_date', $yesterday );
endwhile; endif;
Is there a way to trigger either hook in this situation?
You need to use WooCommerce WC_Data
methods on the WC_Product
object instead of WP postmeta functions.
So try to replace:
update_post_meta($product_id, '_custom_date', $yesterday );
with:
$product->update_meta_data('_custom_date', $yesterday);
$product->save();
Using the save()
method, refresh the product cache (and should also trigger at least one the hooks you mentioned).
In the future, always try to use WooCommerce methods instead of WordPress functions.