使用 Post View Counter 按最常查看的方式对 Woocommerce 产品进行排序 [英] Sort Woocommerce products by most viewed using Post View Counter

查看:23
本文介绍了使用 Post View Counter 按最常查看的方式对 Woocommerce 产品进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法将不胜感激.

我正在尝试使用 post-views-counter 对我的 woocommerce 产品重新排序插件.

遵循这些似乎不起作用的示例按查看次数最多对产品进行排序

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' );

推荐答案

首先,您尝试使用的插件已过时.其次,它似乎创建了一个表来保存视图,这需要更改实际的 MySQL 查询以检索按日期排序的帖子,这是查看您需要做的大量工作.

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;
}

使用 pre_get_posts

这篇关于使用 Post View Counter 按最常查看的方式对 Woocommerce 产品进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆