This members-only tutorial provides the steps to display recently viewed products on single product pages when using WooCommerce in Oxygen.

We shall take the code from here and improve upon it by

  1. changing the display order to the order in which products have been viewed
  2. excluding the current product being viewed and
  3. limiting the number of products to 4

Step 1

WooCommerce keeps track of what products have been viewed using the woocommerce_recently_viewed cookie.

If the Recent Viewed Products widget that comes with WooCommerce is not present on single product pages, this cookie will not be created and used.

But we can use the code given here to set this cookie up even this widget is not used.

Note: As with any cookie-based solution, this will not work reliably when caching is present. You may have to either turn off caching on single product pages or exclude the cookie from being cached.

Install and activate Code Snippets plugin.

Go to Snippets > Add New.

Title: Set "woocommerce_recently_viewed" cookie on product pages

Code:

add_action( 'template_redirect', 'custom_track_product_view', 20 );
/**
 * Set "woocommerce_recently_viewed" cookie on WooCommerce product pages.
 *
 * @author Mike Jolley
 * @link https://github.com/woocommerce/woocommerce/issues/9724#issuecomment-160618200
 * 
 */
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 ) );

}

Set the snippet to run everywhere. Save changes and activate.

Step 2

Let us register the [recently_viewed_products] shortcode.

Create another code snippet.

Title: [recently_viewed_products] shortcode

Code:

This is a premium members-only content.

To view the rest of the content, please sign up for membership ($47/month or $399 one-time).

Already a member? Log in below or here.

Need help implementing a tutorial in your site or want to hire me for custom work?

HIRE ME

Find the article helpful and wish to donate?

DONATE

Comments

You need to be logged in to view and post comments.
Not a member yet? Join here.
magnifiercross
>
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram
%d bloggers like this: