/** * Widget * Display the widget in the sidebar * Save output to the cache if empty * * @param array sidebar arguments * @param array instance */ public function widget($args, $instance) { // Get the most recent products from the cache $cache = wp_cache_get('widget_recent_products', 'widget'); // If no entry exists use array if (!is_array($cache)) { $cache = array(); } // If cached get from the cache if (isset($cache[$args['widget_id']])) { echo $cache[$args['widget_id']]; return false; } // Start buffering ob_start(); extract($args); // Set the widget title $title = apply_filters('widget_title', $instance['title'] ? $instance['title'] : __('Top Rated Products', 'fflcommerce'), $instance, $this->id_base); // Set number of products to fetch if (!($number = absint($instance['number']))) { $number = 5; } // Set up query // Filter the $wpdb query add_filter('posts_clauses', array($this, 'order_by_rating')); // TODO: Only display products that are in stock $query_args = array('posts_per_page' => $number, 'post_type' => 'product', 'post_status' => 'publish', 'meta_query' => array(array('key' => 'visibility', 'value' => array('catalog', 'visible'), 'compare' => 'IN'))); // Run the query $q = new WP_Query($query_args); // If there are products if ($q->have_posts()) { // Print the widget wrapper & title echo $before_widget; if ($title) { echo $before_title . $title . $after_title; } // Open the list echo '<ul class="product_list_widget">'; // Print out each product while ($q->have_posts()) { $q->the_post(); $_product = new fflcommerce_product($q->post->ID); echo '<li>'; // Print the title with a link to the permalink echo '<a href="' . esc_url(get_permalink()) . '" title="' . esc_attr(get_the_title()) . '">'; // Print the product image echo has_post_thumbnail() ? the_post_thumbnail('shop_tiny') : fflcommerce_get_image_placeholder('shop_tiny'); echo '<span class="js_widget_product_title">' . get_the_title() . '</span>'; echo '</a>'; // Print the average rating with html wrappers echo $_product->get_rating_html('sidebar'); // Print the price with html wrappers echo '<span class="js_widget_product_price">' . $_product->get_price_html() . '</span>'; echo '</li>'; } echo '</ul>'; // Close the list // Print closing widget wrapper echo $after_widget; // Reset the global $the_post as this query will have stomped on it wp_reset_postdata(); remove_filter('posts_clauses', array($this, 'order_by_rating')); } // Flush output buffer and save to cache $cache[$args['widget_id']] = ob_get_flush(); wp_cache_set('widget_recent_products', $cache, 'widget'); }