Showing Product View Count on Woo commerce Product Page

前端 未结 2 974
失恋的感觉
失恋的感觉 2020-12-21 11:24

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 p

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 11:44

    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 "
    "; echo ""; echo ""; echo $result; echo " Views
    "; }

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

提交回复
热议问题