I used the below snippet to display a product view counter on the shop page based on the ip address and it worked fine.
add_action('wp', 'product_view_counter');
function product_view_counter() {
global $post;
$userip = $_SERVER['REMOTE_ADDR'];
if ( is_product() ){
$meta = get_post_meta( $post->ID, '_total_views_count', TRUE );
$meta = (!$meta) ? array() : explode( ',', $meta );
$meta = array_filter( array_unique( $meta ) );
if( ! in_array( $userip, $meta ) ) {
array_push( $meta, $userip );
update_post_meta( $post->ID, '_total_views_count', implode(',', $meta) );
}
}
}
Show on Shop page,
add_filter( 'woocommerce_loop_add_to_cart_link','show_product_view_counter_on_product_page',5);
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 = count(explode(',',$meta));
}
echo '<div class="custom-visitor-count"><i class="fa fa-eye"></i><span class="counter-value">'.$count.' Views</span></div>';
}
The new idea is i want to display which 5 attributes or product categories have the most views on another page.
What I've done so far:
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
);
$get_data = get_posts($args);
foreach ($get_data as $gd){
$product = wc_get_product($gd);
$color = $product->get_attribute('pa_color');
$args_color = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'pa_color',
'field' => 'slug',
'terms' => $color,
)),
'fields' => 'ids',
);
$att_color = get_posts($args_color);
$att_color_sum = 0;
foreach($att_color as $ac){
$color = $product->get_attribute('pa_color');
$count_total_color = count($att_color);
$productid_color = $product->get_id();
$meta_color = get_post_meta( $productid_color, '_total_views_count', true);
$count_meta = count(explode(',',$meta_color));
$att_color_sum += $count_meta;
$display = $color." ".$att_color_sum;
}
}
echo "<p> Top 3 color attribute views : ".$display."</p>";
Output it gives a view like this :
Top 3 color attribute views : Blue 15
What i want is like this :
Top 3 color attribute views :
Green : 57
Red : 42
Grey : 24
Obviously, I was lost.
Anyone, please guide me so that I am on the right track.
Sincerely