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:

 * @snippet       [recently_viewed_products] Shortcode - WooCommerce
 * @how-to        Get FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.6.2
 * @donate $9

add_shortcode( 'recently_viewed_products', 'bbloomer_recently_viewed_shortcode' );

function bbloomer_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 = '<h3>Recently Viewed Products</h3>';
	$product_ids = implode( ",", $viewed_products );

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

Leave a Reply