imran khan
imran khan

Reputation: 29

Showing Product View Count on Woo commerce Product Page

i have WordPress site www.kampungcourse.id to choose language program courses. i want to show how many people have watched particular product . using the post view counter plugin it show post view on home page and blog page but not on woo-commerce product pages. can anyone help with custom code to implement this

i tried using post view counter plugin but it does not work on product pages that are part of woo-commerce.

Upvotes: 2

Views: 5955

Answers (4)

osman koçak
osman koçak

Reputation: 1

Explanation:

1.  Recording Views (Cookie-based):
•   When a user visits a product page (is_product()), the code checks if a cookie exists for that product (product_viewed_{product_ID}).
•   If no cookie exists, it increments the view count stored in the product’s metadata (views_count) and then sets a cookie to avoid counting the same user again within 24 hours.
•   The cookie is unique to the product and user, ensuring the count is based on distinct visits.
2.  Displaying Views on Product Page:
•   A custom HTML block is added just before the Add to Cart button to display the number of views for the product.
•   It retrieves the current view count from the product’s meta and outputs it, along with an eye icon from FontAwesome.
3.  Admin Product List Column (Views Count):
•   The code adds a new Views column to the WooCommerce product listing screen in the WordPress admin area.
•   It populates this column with the view count of each product by retrieving the stored metadata.

This gives administrators an easy way to see how many views each product has received directly in the product list.

Advantages of Cookie-based Approach:

•   Better User Tracking: Cookies allow you to track each unique user without relying on their IP address, which can change or be shared across users.
•   More Accurate Count: Avoids repeated counting if the same user revisits the product within the cookie’s lifetime (24 hours in this case).
•   Performance: Cookies are lightweight and don’t require as much server-side processing as tracking IPs in the database.

// Hook to record view count for a product
add_action('wp', function() {
    global $post;

    // Check if we're viewing a single product page
    if (is_product()) {
        // Unique cookie name based on the product ID
        $cookie_name = 'product_viewed_' . $post->ID;

        // Check if the cookie for this product does not exist
        if (!isset($_COOKIE[$cookie_name])) {
            // Retrieve the current view count for the product from post meta
            $meta = get_post_meta($post->ID, 'views_count', true);
            
            // Increment the view count
            $meta = '' !== $meta ? (int)$meta + 1 : 1;

            // Update the view count in the product's meta
            update_post_meta($post->ID, 'views_count', $meta);

            // Set a cookie with the product's view status, expires in 24 hours
            setcookie($cookie_name, '1', time() + 86400, COOKIEPATH, COOKIE_DOMAIN);
        }
    }
});

// Hook to display the view count on the product page (next to the Add to Cart button)
add_action('woocommerce_before_add_to_cart_button', 'add_content_before_addtocart_button_func', 0);

function add_content_before_addtocart_button_func() {
    global $product;
    $id = $product->get_id(); // Get the product ID

    // Retrieve the view count from the product meta
    $meta = get_post_meta($id, 'views_count', true);
    
    // If there's no view count, set it to 0
    $result = !empty($meta) ? $meta : 0;

    // Output the view count in HTML format
    echo "<div class='custom-visitor-count-st' style='font-size: 20px;'>";
    echo "<i class='fa fa-eye'></i>"; // Eye icon (FontAwesome)
    echo "<span class='cv-value'>{$result} Views</span>";
    echo "</div>";
}

// Hook to display the view count in the WooCommerce product list admin screen
add_filter('manage_edit-product_columns', 'add_views_count_column');

function add_views_count_column($columns) {
    $columns['views_count'] = 'Views'; // Add a "Views" column
    return $columns;
}

// Hook to populate the view count in the newly created column
add_action('manage_product_posts_custom_column', 'add_views_count_column_content', 10, 2);

function add_views_count_column_content($column, $post_id) {
    if ($column === 'views_count') {
        // Retrieve the view count from the product meta
        $meta = get_post_meta($post_id, 'views_count', true);
        
        // Display the view count or default to "0" if empty
        echo !empty($meta) ? $meta : '0';
    }
}

Upvotes: 0

Ermelindo Arroyo
Ermelindo Arroyo

Reputation: 21

Here is the updated hook for viewing view count on product page view Let me know if this helped you out.

i will look and make revisions on this one.

Please next time do mention which theme you're using it helps to get answer faster.

add_action('wp', function() { // Adds a function to the 'wp' action hook

    global $post; // Retrieves the global $post variable

    $user_ip = $_SERVER['REMOTE_ADDR']; // Retrieves the IP address of the user

    $meta = get_post_meta( $post->ID, 'views_count', TRUE ); // Retrieves the 'views_count' metadata for the post

    $meta = '' !== $meta ? explode( ',', $meta ) : array(); // Splits the metadata into an array using comma as the delimiter, or creates a new array if the metadata is empty

    $meta = array_filter( array_unique( $meta ) ); // Removes any duplicate IP addresses from the array

    if( ! in_array( $user_ip, $meta ) ) { // Checks if the user's IP address is already in the array

        array_push( $meta, $user_ip ); // Appends the user's IP address to the array

        update_post_meta( $post->ID, 'views_count', implode(',', $meta) ); // Updates the 'views_count' metadata for the post with the modified array, converting it back to a comma-separated string
    }
});

Upvotes: 0

Vaibhavi S.
Vaibhavi S.

Reputation: 1093

Please Replace this function as below to show view on top of page next to rating bar.

add_action( 'woocommerce_before_add_to_cart_button', 'add_content_before_rating_button_func',0 );

    function add_content_before_rating_button_func() {        
                global $product;
                $id = $product->id;         
                $meta = get_post_meta( $id, 'views_count', TRUE );
                if(empty($meta))
                {
                    $result = 0;
                }
                else
                {        
                $result = count(explode(',',$meta)); 
                }       

        ?>
                <script>
                var html="";
                var result = "<?php echo $result ?>";
                html += "<div class='custom-visitor-count-st' style='font-size: 20px;'>";
                html += "<i class='fa fa-eye'></i>";
                html += "<span class='cv-value'>";
                html += result;
                html += " Views</span></div>";

                $(html).insertAfter('.woocommerce-product-rating');
                </script>
                <?php
        }

Upvotes: 0

Vaibhavi S.
Vaibhavi S.

Reputation: 1093

Insert the below code into function.php file. you can insert view count on table by user IP address.

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

Display particular product view count before add to cart button.

add_action( 'woocommerce_before_add_to_cart_button', 'add_content_before_addtocart_button_func',0 );
function add_content_before_addtocart_button_func() {

        global $product;
        $id = $product->id;         
        $meta = get_post_meta( $id, 'views_count', TRUE );
        if(empty($meta))
        {
            $result = 0;
        }
        else
        {        
        $result = count(explode(',',$meta)); 
        }       
        echo "<div class='custom-visitor-count-st' style='font-size: 20px;'>";
        echo "<i class='fa fa-eye'></i>";
        echo "<span class='cv-value'>";
        echo $result;
        echo " Views</span></div>";
}

You can use any other woo commerce hook to display view count.

Upvotes: 0

Related Questions