I am trying to sort the products based on views, view counter is working fine, on findings I found that filter (woocommerce_get_catalog_ordering_args) and I checked this is implemented in woocommerce (/includes/class-wc-query.php Line no 583), it should be working fine but it's sorting product based on latest date instead of the views, I don't know what is causing the problem, can anyone check my code and suggest me the good solution or highlight my mistake.
//Product View Counter
add_action("wp", "product_view_counter");
function product_view_counter() {
global $post;
if ( is_product() ){
$meta = get_post_meta( $post->ID, "_total_views_count", true );
$meta = (int)($meta) ? $meta + 1 : 1;
update_post_meta( $post->ID, "_total_views_count", $meta );
}
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'woo_add_postmeta_ordering_args' );
function woo_add_postmeta_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
if ($orderby_value == "popularity"){
$sort_args['meta_key'] = '_total_views_count';
$sort_args['orderby'] = 'meta_value_num';
$sort_args['order'] = 'desc';
$sort_args['meta_type'] = 'NUMERIC';
}
return $sort_args;
}
Thank you