Reputation: 11
I have installed plugin Post Views Counter and I would like to use those Views to make a new sorting option - "Sort by post views" or "Most popular products".
I have already tried some php function, that I have found:
add_action( 'pvc_after_count_visit', 'update_toolset_view_count' );
function update_toolset_view_count ( $post_id ) {
$post_type = 'product';
// only update the post view count for products
if ($post_type == get_post_type($post_id)) {
$view_count = get_post_meta($post_id, 'wpcf-product-view-count', true);
$view_count = $view_count ? $view_count : 0;
// update and increment the view count for this product
update_post_meta( $post_id, 'wpcf-product-view-count', ( intval($view_count) + 1 ) );
}
}
But it's not working. I mean, post views are very nicely registered when I look into products admin area - so I think post views are saving. But I can't figure how could I use that post views and make new sorting option - "Most popular products" --> products sorted by post views, which I already have.
Upvotes: 0
Views: 692
Reputation: 31
Try this one:
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 );
}
add_filter( 'woocommerce_catalog_orderby', 'misha_add_custom_sorting_options' );
function misha_add_custom_sorting_options( $options ){
$options['popular'] = 'Beliebteste';
return $options;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'misha_custom_product_sorting' );
function misha_custom_product_sorting( $args ) {
// Nach Aufrufen sortieren
if ( isset( $_GET['orderby'] ) && 'popular' === $_GET['orderby'] ) {
$args['meta_key'] = 'product_visit_count';
$args['orderby'] = 'meta_value_num meta_value';
$args['order'] = 'desc';
}
return $args;
}
You have to click on your products at least once before they appear in sorting option.
Upvotes: 2