Show recently viewed products on WooCommerce

February 14, 2020

This feature can increase user experience on your e-commerce. Your customers won’t miss their favorite products thanks to Recently Viewed Products sections. This article introduces 2 free and 1 paid plugins also 1 snippet for it.

1- Recently viewed and most viewed products ( Free )

Also, this plugin is totally free. You can display recently also most viewed products with shortcodes.

Unless you add shortcode to somewhere, it won’t display anything.

As you can see on the picture, you can add shortcode into a post or wherever!
After shortcode, plugin has added the products
Settings page is under WooCommerce Title

2- Wc Recently viewed products ( Free )

It is a totally free plugin.Simply, you display recently viewed products.

After activation, it displays the products on product page automatically. You can set showing product number. Also, you have options to display on shop and cart pages.

It displays the products on Product Page
You can access this settings page under WooCommerce Title

3- Yith WooCommerce recently viewed products ( Paid )

This plugin checks products that users have previously viewed and send tailored emails with special offers.

Show the “recently viewed” section where you want

You can show the section where you want by using a shortcode or simply, you can show it on the Cart page or in My Account area. Also, you can use a widget to show in a sidebar or another widget area.

You can show it by using shortcode

Create unlimited shortcodes with your custom settings

You can build your own shortcode on the settings page. There are many options to detail your product section. You will just have to copy and paste them where you want them to be. Quick and easy.

Show a “Most viewed products” section

Also, you can show most viewed products.

Follow and show every time

Every time, you will follow the products that users look at and you can display them even if your customer change their browsers.

Schedule automatic emails to bring your users back to your shop

This plugin sends attractive e-mails to bring your customers back to your shop automatically.

All Features

  • Display as many suggested products as you want
  • Show only suggested products “In stock”
  • You will have control over the cookies
  • Create a custom page that shows “you looked at these” for every user
  • Sort suggested products by sales, prices, latest viewed, random, or publication date
  • Create a slider for suggested products
  • Send a customized e-mail if a user doesn’t come again since your custom number of day
  • Integrate with Mandrill
  • Add a coupon in the email
  • Shortcodes

Coding Solution

Also, you have a shortcode option thanks to the below snippet. Its usage is simple; there are only simple 3 steps.

You will get a section like this:

Firstly, you will paste the below code to your function.php.

//short code to get the woocommerce recently viewed products
 <?php  function custom_track_product_view() {
    if ( ! is_singular( 'product' ) ) {
        return;
    }

    global $post;

    if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) )
        $viewed_products = array();
    else
        $viewed_products = (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] );

    if ( ! in_array( $post->ID, $viewed_products ) ) {
        $viewed_products[] = $post->ID;
    }

    if ( sizeof( $viewed_products ) > 15 ) {
        array_shift( $viewed_products );
    }

    // Store for session only
    wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}

add_action( 'template_redirect', 'custom_track_product_view', 20 );
 function rc_woocommerce_recently_viewed_products( $atts, $content = null ) {
    // Get shortcode parameters
    extract(shortcode_atts(array(
        "per_page" => '5'
    ), $atts));
    // Get WooCommerce Global
    global $woocommerce;
    // Get recently viewed product cookies data
    $viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] ) : array();
    $viewed_products = array_filter( array_map( 'absint', $viewed_products ) );
    // If no data, quit
    if ( empty( $viewed_products ) )
        return __( 'You have not viewed any product yet!', 'rc_wc_rvp' );
    // Create the object
    ob_start();
    // Get products per page
    if( !isset( $per_page ) ? $number = 5 : $number = $per_page )
    // Create query arguments array
    $query_args = array(
                    'posts_per_page' => $number,
                    'no_found_rows'  => 1,
                    'post_status'    => 'publish',
                    'post_type'      => 'product',
                    'post__in'       => $viewed_products,
                    'orderby'        => 'rand'
                    );
    // Add meta_query to query args
    $query_args['meta_query'] = array();
    // Check products stock status
    $query_args['meta_query'][] = $woocommerce->query->stock_status_meta_query();
    // Create a new query
    $r = new WP_Query($query_args);

    // ----
    if (empty($r)) {
      return __( 'You have not viewed any product yet!', 'rc_wc_rvp' );

    }?>
 <?php while ( $r->have_posts() ) : $r->the_post(); 
   $url= wp_get_attachment_url( get_post_thumbnail_id($post->ID) );

   ?>

   <!-- //put your theme html loop hare -->
 <li >
    <a class="product-picture" href="<?php echo get_post_permalink(); ?>" title="Show details for Watches">
        <img alt="Picture of Watches" src="<?php echo $url;?>" title="Show details for Watches" />
    </a>
<a class="product-name" href="<?php echo get_post_permalink(); ?>"><?php the_title()?></a>
</li>   
<!-- end html loop  -->
<?php endwhile; ?>



    <?php wp_reset_postdata();
    return '<div class="woocommerce columns-5 facetwp-template">' . ob_get_clean() . '</div>';
    // ----
    // Get clean object
    $content .= ob_get_clean();
    // Return whole content
    return $content;
}
// Register the shortcode
add_shortcode("woocommerce_recently_viewed_products", "rc_woocommerce_recently_viewed_products");
    ?>

You can look at the resource from Github by clicking here.

Now, you can display it wherever with below shortcode.

[woocommerce_recently_viewed_products]

Also you can custom your displaying settings.

Here are some usefull change:

Change product number per section

As a default, the snippet shows up to 5 products on a recently viewed products section. You have two options to set your target product number.

Via per_page attribute in the shortcode, you can set it. For example, if you want to show maximum 2 products on a section, you should use the below shortcode:

[woocommerce_recently_viewed_products per_page="2"]

But this way needs the per_page attribute for every shortcode. If you want to set a new absolute number, you can follow the below steps.

Note: After this change, per_page attribute won’t work anymore.

Find below code in the snippet:

// Get products per page
    if( !isset( $per_page ) ? $number = 5 : $number = $per_page )
        // Create query arguments array
        $query_args = array(
            'posts_per_page' => $number,
            'no_found_rows'  => 1,
            'post_status'    => 'publish',
            'post_type'      => 'product',
            'post__in'       => $viewed_products,
            'orderby'        => 'rand'
        );

And change $number with your goal.For example, to display maximum 7 products on a section, you should change it like this:

// Get products per page
    if( !isset( $per_page ) ? $number = 5 : $number = $per_page )
        // Create query arguments array
        $query_args = array(
            'posts_per_page' => 7,
            'no_found_rows'  => 1,
            'post_status'    => 'publish',
            'post_type'      => 'product',
            'post__in'       => $viewed_products,
            'orderby'        => 'rand'
        );

That’s it. Now, every short-code will use your absolute target number while display. So, you don’t need to use the same attributes in every shortcode.

By following WooFocus, you can learn more WooCommerce Tutorials & Tricks.

Tags

What do you think?

What do you think?

22 Comments:
August 29, 2024

You may also think of insurance in case you see
an Ace from the dealer. Make sure you know what you want to play with and never exceed that.

August 31, 2024

Точно важные новинки подиума.
Исчерпывающие события всемирных подуимов.
Модные дома, бренды, haute couture.
Самое лучшее место для модных хайпбистов.
https://permgorod.ru/novosti/252-zhitelnitsu-permi-oshtrafovali-iz-za-raduzhnogo-flaga-v-okne/

September 3, 2024

Самые свежие события индустрии.
Все мероприятия известнейших подуимов.
Модные дома, бренды, высокая мода.
Лучшее место для стильныех хайпбистов.
https://simferopol.rftimes.ru/news/2024-05-03-fotovystavka-bitva-za-krym-put-k-osvobozhdeniyu-otkrylas-v-simferopole

September 5, 2024

Очень свежие новости модного мира.
Все эвенты лучших подуимов.
Модные дома, лейблы, haute couture.
Лучшее место для модных людей.
https://ryazansport.ru/sport/pobeda-manchester-yunayted-nad-seltikom.html

September 5, 2024
September 6, 2024
September 13, 2024

Стильные советы по подбору превосходных видов на каждый день.
Заметки экспертов, новости, все новые коллекции и шоу.
https://emurmansk.ru/pub/2024-09-10-demna-gvasaliya-revolyutsioner-mody-i-kreativnyy-provokator/

September 22, 2024

Thanks for every other magnificent article. Where else could anybody get that kind of info in such a perfect manner of writing? I have a presentation next week, and I am at the search for such info.

September 25, 2024

Стильные советы по созданию отличных луков на любой день.
Мнения стилистов, новости, все дропы и мероприятия.
https://luxe-moda.ru/chic/499-10-maloizvestnyh-faktov-o-demne-gvasalii/

October 22, 2024

Этот PHP Shell является полезным инструментом для системы или веб-администратора, чтобы сделать удаленное управление без использования CPanel, подключении с помощью SSH, FTP и т.д. Все действия происходят в веб-браузере.
Скачать: https://hackmode.ru/showthread.php?t=38

October 27, 2024

Thank you for your whole effort on this website. My daughter take interest in carrying out investigation and it’s really obvious why. I notice all concerning the lively way you produce helpful things by means of this web blog and as well as foster participation from others about this concept while our favorite princess is now learning a great deal. Have fun with the remaining portion of the year. You are always doing a wonderful job.

October 30, 2024
October 31, 2024

I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you? Plz respond as I’m looking to design my own blog and would like to know where u got this from. thanks

November 8, 2024

priligy kaufen Viability after doxorubicin exposure was slightly greater for the two clones expressing Myr Akt compared with the vector clone 1

November 15, 2024

Hello my loved one! I wish to say that this post is awesome, great written and include almost all significant infos. I’d like to peer extra posts like this.

November 16, 2024

I’ve read a few good stuff here. Certainly worth bookmarking for revisiting. I wonder how much effort you put to make such a wonderful informative website.

Do not take WP Thyroid and Nature Throid either alone or in combination with other medicines, for the treatment of obesity or weight loss how can i get cheap cytotec price

I’m typically to blogging and i actually appreciate your content. The article has actually peaks my interest. I’m going to bookmark your site and preserve checking for brand spanking new information.

January 18, 2025

На этом сайте вы сможете найти подробную информацию о препарате Ципралекс. Здесь представлены информация о основных показаниях, дозировке и вероятных побочных эффектах.
http://SunnysideCampground-usa.omob.xyz/category/website/wgI2vZFhZf5rbhFqBTP7G0CD1

January 21, 2025

На данном сайте вы сможете найти подробную информацию о препарате Ципралекс. Здесь представлены информация о показаниях, дозировке и возможных побочных эффектах.
http://KopyongKoreaRepublicof.auio.xyz/category/website/wgI2vZFhZf5rbhFqBTP7G0CD1

February 16, 2025

На этом сайте у вас есть возможность приобрести виртуальные телефонные номера различных операторов. Они могут использоваться для регистрации профилей в различных сервисах и приложениях.
В ассортименте доступны как постоянные, так и временные номера, что можно использовать чтобы принять сообщений. Это простое решение для тех, кто не хочет использовать личный номер в сети.
виртуальный номер смс
Оформление заказа очень удобный: определяетесь с необходимый номер, оплачиваете, и он сразу становится готов к использованию. Попробуйте сервис уже сегодня!

Leave a Reply

Your email address will not be published. Required fields are marked *

More notes