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?

13 Comments:
June 12, 2025

Founded in 2001 , Richard Mille redefined luxury watchmaking with cutting-edge innovation . The brand’s iconic timepieces combine aerospace-grade ceramics and sapphire to enhance performance.
Drawing inspiration from the precision of racing cars , each watch embodies “form follows function”, ensuring lightweight comfort . Collections like the RM 001 Tourbillon set new benchmarks since their debut.
Richard Mille’s experimental research in materials science yield skeletonized movements crafted for elite athletes.
Certified Mille Richard RM3502 prices
Beyond aesthetics , the brand pushes boundaries through limited editions tailored to connoisseurs.
Since its inception, Richard Mille epitomizes modern haute horlogerie, appealing to global trendsetters.

June 12, 2025

The Audemars Piguet Royal Oak, redefined luxury watchmaking with its signature angular case and stainless steel craftsmanship .
Available in classic stainless steel to skeleton dials , the collection combines avant-garde design with precision engineering .
Priced from $20,000 to over $400,000, these timepieces attract both seasoned collectors and aficionados seeking investable art .
Real AP Royal Oak 26240 or wristwatch
The Royal Oak Offshore push boundaries with innovative complications , showcasing Audemars Piguet’s technical prowess .
Thanks to ultra-thin calibers like the 2385, each watch reflects the brand’s commitment to excellence .
Explore exclusive releases and detailed collector guides to deepen your horological expertise with this modern legend .

June 13, 2025

ultimate AI porn maker generator. Create hentai art, porn comics, and NSFW with the best AI porn maker online. Start generating AI porn now!

June 13, 2025

Die Royal Oak 16202ST kombiniert ein rostfreies Stahlgehäuse von 39 mm mit einem ultradünnen Design von nur 8,1 mm Dicke.
Ihr Herzstück bildet das automatische Manufakturwerk 7121 mit erweitertem Energievorrat.
Der blaue „Bleu Nuit“-Ton des Zifferblatts wird durch das Petite-Tapisserie-Muster und die kratzfeste Saphirscheibe mit Antireflexbeschichtung betont.
Neben Stunden- und Minutenanzeige bietet die Uhr ein praktisches Datum bei Position 3.
AP Royal Oak 15407st herrenuhren
Die 50-Meter-Wasserdichte macht sie alltagstauglich.
Das geschlossene Stahlband mit verstellbarem Dornschließe und die achtseitige Rahmenform zitieren das ikonische Royal-Oak-Erbe aus den 1970er Jahren.
Als Teil der „Jumbo“-Kollektion verkörpert die 16202ST meisterliche Uhrmacherkunst mit einem Wertanlage für Sammler.

June 14, 2025

Стальные резервуары используются для сбора нефтепродуктов и соответствуют стандартам давления до 0,04 МПа.
Горизонтальные емкости изготавливают из нержавеющих сплавов с усиленной сваркой.
Идеальны для АЗС: хранят бензин, керосин, мазут или авиационное топливо.
пожарные резервуары для воды
Двустенные резервуары обеспечивают защиту от утечек, а подземные модификации подходят для разных условий.
Заводы предлагают типовые решения объемом до 500 м³ с технической поддержкой.

June 14, 2025

Space XY is a superb game with a lot of assets. You can work out a strategy and play at minimum risk, enjoying the game. Considering the fact that the game is developed by a well-known provider BGaming, and it has a fair mechanism of the game, the risks are minimal for users. Experience the cosmos like never before! The BGaming team proudly presents an innovative gaming experience. Dive into ‘Space XY’, a groundbreaking game where you’ll virtually board a space rocket and soar to unparalleled heights. Monitor your rocket’s journey through the X and Y axes, place wagers, and steer your ship towards the stars! Multiply your bets, aim for the highest multipliers, and seize substantial rewards. But remember, to secure your winnings, you must disembark the rocket before it shatters. Prepare for lift-off; endless adventures beckon.
https://tempcresenther1976.bearsfanteamshop.com/extra-resources
It’s time to soar to new heights with BGaming! Launching the rocket to the stars means getting incredible winnings! Space XY is an exciting game with easy gameplay. Don’t hesitate to join a breathtaking ride to the stars and make a fortune. Space XY is one of the most exhilarating games you’ll find in the online casino universe. It combines the thrill of space exploration with the excitement of real-time gambling, where every second counts. Whether you’re a casual player or a serious gambler looking for big wins, this crash-style game offers the perfect mix of fun, strategy, and high-stakes action. Trust me this game booster is amazing, it helps the lag to a minimum and even enhances graphics. You don’t even need to pay which is the best part. But after using it for a week, it made my whole ipad slow. I had to reinstall it to fix the issue. Other than that its great. Its in chinese, but just type the game in english and find the icon.

June 14, 2025

Ce modèle Jumbo arbore un acier poli de 39 mm ultra-mince (8,1 mm d’épaisseur), équipé du calibre automatique 7121 offrant une autonomie étendue.
Le cadran « Bleu Nuit Nuage 50 » présente un guillochage fin associé à des chiffres luminescents et des aiguilles Royal Oak.
Une verre inrayable traité garantit une lisibilité optimale.
Montres coûteuses Audemars Royal Oak 15400st – informations
Outre l’heure traditionnelle, la montre intègre une indication pratique du jour. Étanche à 5 ATM, elle résiste aux éclaboussures et plongées légères.
Le bracelet intégré en acier et la carrure à 8 vis reprennent les codes du design signé Gérald Genta (1972). Un fermoir déployant sécurisé assure un maintien parfait.
Appartenant à la collection Extra-Plat, ce garde-temps allie savoir-faire artisanal et élégance discrète, avec un prix estimé à plus de 75 000 €.

June 15, 2025

Crafted watches are still sought after for several key reasons.
Their handmade precision and heritage set them apart.
They symbolize status and success while mixing purpose and aesthetics.
Unlike digital gadgets, their value grows over time due to exclusive materials.
https://www.verdoos.com/read-blog/28274
Collectors and enthusiasts admire the intricate movements that no battery-powered watch can replace.
For many, collecting them defines passion that lasts forever.

Коллекция Nautilus, созданная мастером дизайна Жеральдом Гентой, сочетает спортивный дух и высокое часовое мастерство. Модель Nautilus 5711 с самозаводящимся механизмом имеет энергонезависимость до 2 дней и корпус из нержавеющей стали.
Восьмиугольный безель с плавными скосами и синий солнечный циферблат подчеркивают уникальность модели. Браслет с интегрированными звеньями обеспечивает комфорт даже при активном образе жизни.
Часы оснащены функцией даты в позиции 3 часа и сапфировым стеклом.
Для сложных модификаций доступны хронограф, вечный календарь и индикация второго часового пояса.
https://patek-philippe-nautilus.ru/
Например, модель 5712/1R-001 из красного золота 18K с механизмом на 265 деталей и запасом хода до 48 часов.
Nautilus остается предметом коллекционирования, объединяя современные технологии и традиции швейцарского часового дела.

June 16, 2025

Gambling is becoming an engaging way to enhance your gaming journey. Placing wagers on football, our platform offers exceptional value for all players.
With in-play wagering to scheduled events, access a broad selection of betting markets tailored to your interests. The easy-to-use design ensures that placing bets is both straightforward and reliable.
https://www.dlife.co.jp/pages/mostbet_pakistan_official_site___sports_betting___casino_with_bonuses.html
Sign up today to enjoy the top-tier gaming available on the web.

Размещение систем видеонаблюдения поможет безопасность территории на постоянной основе.
Инновационные решения гарантируют четкую картинку даже в темное время суток.
Вы можете заказать различные варианты оборудования, адаптированных для офиса.
сколько стоит установка видеонаблюдения
Качественный монтаж и сервисное обслуживание делают процесс простым и надежным для любых задач.
Обратитесь сегодня, чтобы получить персональную консультацию для установки видеонаблюдения.

На данном сайте доступен мессенджер-бот “Глаз Бога”, который проверить всю информацию о гражданине из открытых источников.
Сервис работает по ФИО, анализируя публичные материалы в Рунете. Через бота доступны 5 бесплатных проверок и детальный анализ по фото.
Инструмент проверен на август 2024 и охватывает аудио-материалы. Бот поможет проверить личность в соцсетях и предоставит информацию мгновенно.
глаз бога поиск по телеграм
Данный инструмент — помощник для проверки персон удаленно.

Здесь доступен сервис “Глаз Бога”, который собрать всю информацию о гражданине через открытые базы.
Бот работает по фото, обрабатывая публичные материалы в Рунете. С его помощью доступны бесплатный поиск и детальный анализ по фото.
Сервис обновлен согласно последним данным и охватывает фото и видео. Сервис гарантирует найти профили в открытых базах и покажет результаты в режиме реального времени.
глаз бога телеграмм канал
Данный бот — идеальное решение при поиске граждан онлайн.

Leave a Reply

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

More notes