Home » WooCommerce: Recently Viewed Products (Shortcode)

WooCommerce: Recently Viewed Products (Shortcode)

by Tutor Aspire

Currently, you can use a widget to have the user see the list of products they recently viewed. This is great and sooner or later it will also become a Gutenberg block I believe.

But for now, let’s create our own shortcode… and let’s take advantage of the existing [products] shortcode and learn how we can “pass” product IDs to it without the need of reinventing the wheel.

This snippet teaches you where recently viewed products are stored (spoiler: in a cookie) and also how to use an existing shortcode… inside a new shortcode. Enjoy!

“Recently viewed” section after using my brand new [recently_viewed_products] WooCommerce shortcode

PHP Snippet: Create a [recently_viewed_products] Shortcode

Note: if you see no recent products it’s because you still need to have a Recently Viewed Products widget active. Thankfully there is a fix if you don’t need the widget: https://businessbloomer.com/woocommerce-recently-viewed-products-shortcode/#comment-246536

/**
 * @snippet       [recently_viewed_products] Shortcode - WooCommerce
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 5.1
 * @donate $9     https://tutoraspire.com
 */

add_shortcode( 'recently_viewed_products', 'tutoraspire_recently_viewed_shortcode' );

function tutoraspire_recently_viewed_shortcode() {

$viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) : array();
$viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );

if ( empty( $viewed_products ) ) return;

$title = '

Recently Viewed Products

'; $product_ids = implode( ",", $viewed_products ); return $title . do_shortcode("[products ids='$product_ids']"); }

You may also like