Sort and display all products by most viewed in WooCommerce Sort and display all products by most viewed in WooCommerce wordpress wordpress

Sort and display all products by most viewed in WooCommerce


For that all other products (not viewed yet) should need to have product_visit_count meta key with a meta value of 0.

You can do that by adding this simple function, that you will run once (always make a database backup):

// Function that set "product_visit_count" metakey with a zero value on non visited productsfunction set_zero_product_visit_count_on_not_visited_products() {    // Only for admin user role    if( ! current_user_can('edit_products')) return;    // Get all products that doesn't have "product_visit_count" as metakey (not visited)    $product_ids = wc_get_products( array(        'limit'         => -1,        'return'        => 'ids',        'meta_key'      => 'product_visit_count',        'meta_compare'  => 'NOT EXISTS',    ) );        // Loop through product ids    foreach( $product_ids as $product_id ) {        // Add 'product_visit_count' meta key with a value of 0 (zero)        update_post_meta( $product_id, 'product_visit_count', 0 );    }}// Triggers the functionset_zero_product_visit_count_on_not_visited_products();

Code goes in functions.php file of your active child theme (or active theme).

Once saved, as an administrator user role, browse any page of your web site, this execute the function. Now you can remove it (delete it). Tested and works.


Now for your new upcoming products, when you will add a new product, the following script will add product_visit_count meta key with a meta value of 0:

add_action( 'woocommerce_admin_process_product_object', 'init_product_visit_count_on_new_prodct' );function init_product_visit_count_on_new_prodct( $product ) {    // Get 'product_visit_count' meta value    $meta_value = $product->get_meta( 'product_visit_count' );        // If meta value doesn't exist    if ( empty($meta_value) ) {        // Set the 'product_visit_count' to zero        $product->update_meta_data( 'product_visit_count', 0 );    }}

Code goes in functions.php file of your active child theme (or active theme). It should work.