Clearing the WooCommerce shortcodes cache to use sorting

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

WooCommerce come with few shortcodes which come in handy for front side products display. While sort is being applied to those shortcodes too, they use transient data (cache) which makes a sort update to not apply. The cache data use quite long life, 30 days, so it’s useless to wait for it to expire for the code to run again.

Shortcode example


|product_category category="featured" per_page="12" columns="4"|

Unfortunate WooCommerce developers didn’t provided a way to clear the cache, so this need to be done manually through a database management application like phpMyAdmin or programatically when updating a WooCommerce sort type.

The following code, should be placed inside the active theme functions.php or included within a plugin which need to be active. This check on every order update if the sort is a WooCommerce one (use products) then clear the cache from the _options table to ensure shortcode code will run again and include the new order.

    add_action('apto_order_update_complete', 'custom_apto_order_update_complete');
    function custom_apto_order_update_complete( $sort_view_id )
        {
            
            global $APTO;
            
            $sort_view_data     =   get_post($sort_view_id);
            if($sort_view_data->post_parent > 0)
                $sortID             =   $sort_view_data->post_parent;
                else
                $sortID             =   $sort_view_id;
                
            $sort_settings          =   $APTO->functions->get_sort_settings($sortID);
            $sort_post_types        =   isset($sort_settings['_rules']['post_type']) ?  $sort_settings['_rules']['post_type']   :   array();
            
            //continue only if post type rules is 'product'
            if( count($sort_post_types) !==    1    ||  array_search('product', $sort_post_types)   === FALSE )
                return;
                         
            global $wpdb;
            
            $mysql_query            =   "DELETE FROM " . $wpdb->options . "
                                            WHERE `option_name` LIKE '%_wc_loop%'";
            $results                =   $wpdb->get_results( $mysql_query );

                
        }