Custom woocommerce product view counter using hooks

Custom woocommerce product view counter using hooks

Nov 14, 2018 | PHP, WordPress

In this tutorial “Custom woocommerce product view counter using hooks” we learn to display particular user count first need IP Address of user. User “$_SERVER[‘REMOTE_ADDR’]” we can get the IP address of user.

$_SERVER is an array containing information such as headers, paths, and script locations. “REMOTE_ADDR”, The IP address from which the user is viewing the current page.

Using the below code we will insert user IP address , post id and meta key(_views_count) in wp_postmeta table.

add_action('wp', function() {

global $post;

$user_ip = $_SERVER['REMOTE_ADDR'];

$meta = get_post_meta( $post->ID, '_views_count', TRUE );

$meta = '' !== $meta ? explode( ',', $meta ) : array();
$meta = array_filter( array_unique( $meta ) );

if( ! in_array( $user_ip, $meta ) ) {

array_push( $meta, $user_ip );
update_post_meta( $post->ID, '_views_count', implode(',', $meta) );
}
});

Now using the below woocommerce hook, We can display particular product view count after add to cart button.

add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func',0 );
function add_content_after_addtocart_button_func() {

        global $product;
        $id = $product->id;         
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $meta = get_post_meta( $id, '_se_post_views', TRUE );
        if(empty($meta))
        {
            $result = 0;
        }
        else
        {        
        $result = count(explode(',',$meta)); 
        }       
        echo "<div class='custom-visitor-count-st'>";
        echo "<i class='fa fa-eye'></i>";
        echo "<span class='cv-value'>";
        echo $result;
        echo " Views</span></div>";
}

At the end we have to use the below woocommerce hook, We can display particular product’s view count after every product listing on shop page.

add_action('woocommerce_after_shop_loop_item','show_free_shipping', 20);
function show_free_shipping () {

        global $product;
        $id = $product->id;         
        $user_ip = $_SERVER['REMOTE_ADDR'];
        $meta = get_post_meta( $id, '_se_post_views', TRUE );
        if(empty($meta))
        {
            $result = 0;
        }
        else
        {        
        $result = count(explode(',',$meta)); 
        } 
        echo "<div class='related-custom-count'><i class='fa fa-eye'></i>";
        echo "<span class='cv-value'>";
        echo $result;
        echo "</span></div>";
}

 

Thank you for being here, Please share your feedback in below comment section.

Being Idea is a web platform of programming tutorials to make better programming skills and provides Software Development Solutions.

0 Comments

Leave a Reply