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
- changing the display order to the order in which products have been viewed
- excluding the current product being viewed and
- 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 $599 one-time).
Already a member? Log in below or here.