I have a woocommerce website, and I need to display the number of views for each product on the product page. How can I achieve this functionality without a plugin? Is there a way to use a custom function or a snippet of code that can do the track and show the product views? Any help or guidance would be appreciated. Thank you.
You can use a custom meta field to store the number of views for each product. You can use the woocommerce_before_single_product action hook to update the meta field whenever a product page is loaded. Then you can use the woocommerce_single_product_summary action hook to display the meta field value on the product page. Here is an example of how you could do it:
// Update product view count
add_action( 'woocommerce_before_single_product', 'update_product_view_count' );
function update_product_view_count() {
// Get the current product ID.
$product_id = get_the_ID();
// Get the current view count for the product.
$view_count = get_post_meta( $product_id, '_product_view_count', true );
// If the view count is empty, set it to 0.
if ( empty( $view_count ) ) {
$view_count = 0;
}
// Increment the view count by 1.
$view_count++;
// Update the view count metadata.
update_post_meta( $product_id, '_product_view_count', $view_count );
}
// Display product view count
add_action( 'woocommerce_single_product_summary', 'display_product_view_count', 25 );
function display_product_view_count() {
$product_id = get_the_ID();
$view_count = get_post_meta( $product_id, '_product_view_count', true );
if ( ! empty( $view_count ) ) {
echo '<p class="product-view-count">Product Views ' . $view_count . '</p>';
}
}