DEV Community

Aman Mehra
Aman Mehra

Posted on

Custom WooCommerce Product View Counter

The product view counter is a count of the total page view of that specific product page. This means when someone visits your product page then this counter will auto-increment each time. It will increment one by one and show you the total views of that page.

Why you should add it? Because it is a very powerful impression for visitors and when they look this product has that many views then it will think about to go with this product and have it.

Custom WooCommerce Product View Counter

To make a custom product view counter in woocommerce, we will make a hook function to add a post meta field in the wp_postmeta table.

Functions reference:

  • To get the post meta field based on product ID get_post_meta()
  • To update the post meta field update_post_meta()
  • To show counter on product page woocommerce_before_add_to_cart_button
  • To show counter on shop page or archove page woocommerce_after_shop_loop_item
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 = ($meta) ? $meta + 1 : 1;  
             update_post_meta( $post->ID, '_total_views_count', $meta ); 
         } 

} 
Enter fullscreen mode Exit fullscreen mode

Add the above code in your active theme’s functions.php file, I’ll recommend using a child theme for any functionality.

Show them on the product page.

add_action( 'woocommerce_before_add_to_cart_button', 'show_product_view_counter_on_product_page', 10); 
    function show_product_view_counter_on_product_page() { 

        global $product; 
        $id = $product->id;          
        $meta = get_post_meta( $id, '_total_views_count', true); 
        if(!$meta) { 
            $count = 0; 
        } else {         
            $count = $meta;  
        }        
        echo "<div class="custom-visitor-count"><i class="fa fa-eye"></i><span class="counter-value">".$count." Views</span></div>"; 

} 
Enter fullscreen mode Exit fullscreen mode

You can also show the counter on product archive page/shop page with this action hook woocommerce_after_shop_loop_item.

And also make a conditions in the code for product view counter based on IP address.

Discussion (0)