Tamlyn Holmes
Tamlyn Holmes

Reputation: 11

Sort Woocommerce products by most viewed using Post View Counter

Any ideas would be much appreciated.

I am trying to reorder my woocommerce products by most viewed using the post-views-counter plugin.

Followed these examples which did not seem to work Sort products by most viewed

function my_view_filter($query){
  if ($query->is_main_query() && ( $query->is_home() || $query- >is_archive() 
   )
     ) {
     $query->set('post_type', 'product');
     $query->set('suppress_filters', false);
     $query->set('orderby', 'post_views');
     $query->set('order', 'asc');
     $query->set('fields', '');
     }
   }
add_action( 'pre_get_posts', 'my_view_filter' );

Upvotes: 1

Views: 1511

Answers (2)

Maulik patel
Maulik patel

Reputation: 2432

// Remove product category/tag meta from its original position
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );
// Add product meta in new position
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 5 );

Upvotes: 0

Ali_k
Ali_k

Reputation: 1661

First of all, the plugin you're trying to use is outdated. Secondly, it seems to create a table to hold the views and this would require changing the actual MySQL query to retrieve posts ordered by date which is a lot of work looking what you need to do.

You could simply just save views on visit to post meta and use that to order products on the catalog like this:

/**
 * Setting post count on each visit
 *
 */
add_action( 'woocommerce_before_single_product', 'prefix_save_product_views' );
function prefix_save_product_views(  ) {

    $product_id = get_the_ID();
    $increment = 1;
    $current_visit_count = get_post_meta( $product_id, 'product_visit_count', true );

    $total_visit_count = (int)$current_visit_count + $increment;
    update_post_meta( $product_id, 'product_visit_count', $total_visit_count );

}

/**
 * Change the display order based on visit count only in Catalog
 *
 */
add_filter('woocommerce_get_catalog_ordering_args', 'prefix_woocommerce_catalog_orderby');
function prefix_woocommerce_catalog_orderby( $args ) {
    $args['meta_key'] = 'product_visit_count';
    $args['orderby'] = 'meta_value_num';
    $args['order'] = 'desc';
    return $args;
}

You'd run into multiple issues using pre_get_posts

Upvotes: 4

Related Questions