'Clear WooCommerce Cache Programatically, Unable to Filter Products by Attributes

At a loss here. If I log into the backend and update a product in the dashboard to add/remove an attribute, the cache will be cleared properly and the product will filter properly. All works as it should.

However, I need to add/update products programmatically.

I’ve tried the following:

$wc_data_store = new ReflectionMethod(‘WC_Product_Data_Store_CPT’, ‘update_lookup_table’);
$wc_data_store->setAccessible(true);

/// update product code goes here

wp_cache_delete($post_id, ‘post_meta’);
if (isset($wc_data_store)) $wc_data_store->invokeArgs(new WC_Product_Data_Store_CPT, array($success, ‘wc_product_meta_lookup’));

… and when that didn’t work, I tried a custom method after each product update …

// update product code goes here … then call following procedure each product to clear cache
public static function flushCacheUpdateLookupTable($the_product)
{
$product = wc_get_product($the_product);
if ($product) {
$id = $product->get_id();
wc_delete_product_transients($id);
wp_cache_delete($id, ‘post_meta’);
wp_cache_delete($id, ‘posts’);
wp_cache_delete(‘lookup_table’, ‘object_’ . $id);
$productType = $product->get_type();

$datastoreType = ‘product’;
switch ($productType) {
case ‘variable’:
case ‘grouped’:
case ‘variation’:
$datastoreType .= ‘-‘ . $productType;
}
$data_store = \WC_Data_Store::load($datastoreType);

if (method_exists(‘WC_Product_Data_Store_CPT’, ‘update_lookup_table’)) {
$product_data_store = new \WC_Product_Data_Store_CPT();
$reflection = new \ReflectionMethod($product_data_store, ‘update_lookup_table’);
if ($reflection->isPublic()) {
$data_store->update_lookup_table($id, ‘wc_product_meta_lookup’);
} else {
//in the meantime an increase of zero in the product sales will force the update…
$data_store->update_product_sales($id, 0, ‘increase’);
}
}
}
}

I’ve tried to go into the tools and manually press every button to do with clearing transients, rebuilding, regenerating, etc. I can’t get the cache to clear properly so that the products are filtered by attribute unless I go into the product and manually add/remove the attributes to trigger the updating of the attribute cache (this isn't a viable option since we are talking about hundreds of products each day that are updated).

Any thoughts are appreciated, been at this for a few days now without anything working.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source