WooCommerce Recently Viewed Products Shortcode Plugin

WooCommerce Recently Viewed Products Shortcode Plugin

A few days ago, WooThemes team announced version 2 of the very popular WooCommerce plugin that allows every single WordPress website to sell any kind of products very easily. Even if i’m more used to work with the awesome Easy Digital Downloads plugin, by the very talented Pippin Williamson, i wanted to go a bit deeper into WooCommerce and show you how you can use existing features to create new functions. And today i’d like to explain you how to create a shortcode that displays recently viewed products. Recently viewed products is an incredibly powerful feature simply because it’s, for me, sort of very basic artificial intelligence. It allows users to easily go back to products they already viewed in just a matter of seconds. And the fact to use a shortcode to display recently viewed products is great because you can place it everywhere in your website.

Normally when i create a tutorial on WPexplorer i explain step by step the method, but as today’s tuto is a bit longer, i prefer to explain the whole process and then to provide you the full code with comments directly into the code.

Doing it within a shortcode

So, we’re going to create a plugin that will register a [woocommerce_recently_viewed_products per_page=”5″] shortcode. Why creating a plugin? Because it’s the easiest way to store a feature that you can use with any theme. If you decide to register a shortcode into a theme, the shortcode will be available only if the theme is activated. With a plugin, no matter the theme you’re using, the feature will still be available. Another very important thing, is that you should never ever modify WooCommerce files.

Do you like cookies? I really do!

By default WooCommerce creates a cookie that stores important data about what a visitor does and sees on the shop. And that’s exactly the type of data we need to create our plugin. The most important data we need are stored into a cookies called $_COOKIE[‘woocommerce_recently_viewed’]. Basically this cookie stores the ID of the lastest viewed products. As WooCommerce is already saving these IDs, our job is finally to create the good query using the “post__in” query attribute and to ensure that the products we need to display are still in stock. To do so, we need to use the $woocommerce->query->stock_status_meta_query() method into the “meta_query” query attribute.

The plugin complete code

As the code is pretty simple i added the comments directly into the code, and i didn’t do a step by step tutorial, but if something isn’t clear please write a comment and i’ll be more than happy to explain you each part of the code!

<?php
/*
Plugin Name: WooCommerce - Recently Viewed Products
Plugin URL: http://remicorson.com/
Description: Adds a "recently viewed products" shortcode
Version: 1.0
Author: Remi Corson
Author URI: http://remicorson.com
Contributors: corsonr
Text Domain: rc_wc_rvp
Domain Path: languages
*/

/**
 * Register the [woocommerce_recently_viewed_products per_page="5"] shortcode
 *
 * This shortcode displays recently viewed products using WooCommerce default cookie
 * It only has one parameter "per_page" to choose number of items to show
 *
 * @access      public
 * @since       1.0 
 * @return      $content
*/
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 query return results
	if ( $r->have_posts() ) {

		$content = '<ul class="rc_wc_rvp_product_list_widget">';

		// Start the loop
		while ( $r->have_posts()) {
			$r->the_post();
			global $product;

			$content .= '<li>
				<a href="' . get_permalink() . '">
					' . ( has_post_thumbnail() ? get_the_post_thumbnail( $r->post->ID, 'shop_thumbnail' ) : woocommerce_placeholder_img( 'shop_thumbnail' ) ) . ' ' . get_the_title() . '
				</a> ' . $product->get_price_html() . '
			</li>';
		}

		$content .= '</ul>';

	}

	// 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");
Remi
Remi is an expert WordPress developer that coded many great free and premium themes and plugins. His experience on WordPress allows him to produce great stuff and to propose advanced tutorials. (remicorson.com)
Remi
This article has 27 comments
  1. AJ Clarke | WPExplorer says:

    Love to see you are using ‘no_found_rows’ => 1 – keeping WordPress fast one query at a time!

    Admin
    1. Remi says:

      yeah, no_found_rows is very useful for queries that don’t need pagination, it avoids to use SQL_CALC_FOUND_ROWS in the query when it’s not needed. That makes a better and faster query.

      Author
  2. David Kartuzinsli says:

    Fabulous! Thank you for your time on this.

    1. Remi says:

      You’re welcome!

      Author
  3. Aakash Rohilla says:

    Yes! Woo is famous for their E-Commerce Themes and Plugins for WordPress. Thanks for the info.

  4. Szymon says:

    I’ve scoured WooCommerce and I can’t find a way to make Terms & Conditions box that people have to click to say that they’ve read and agree, when they go to the checkout page.

    Is this possible? And if so, how?

    1. Remi says:

      Hi, i think you should ask directly to Woo team, they have a great support.

      Author
  5. BRS says:

    Thanks for this. I tried it out and it added a bullet before my product title. I can’t seem to get that to go away, even if I delete the plugin code. Any suggestions?

  6. BRS says:

    Nevermind. Had to remove another widget to get it to go away

  7. josephorr says:

    What directory do I save this PHP file into?

  8. josephorr says:

    Neeeeevermind

  9. josephorr says:

    Okay, I’ve tried the code you supplied, saved it in plugins, but I cannot seem to get the products to populate. Do I need Woo 2.0 for this? You can see the “You have not viewed any products yet!” at the bottom of this page “http://spectraminerals.com/”

  10. vikas says:

    how can increase the related products in woocommerce.I want to more than 20 related products.

  11. Asi says:

    Hi Remi. Thank you for your codes.
    How can I change this codes in order to add an extra field setting to this widget :
    I want in plugin’s widget setting I would be able to select a category to display Recently Viewed Products from only that category (not from all products)

    because I wanna use this widget in different sidebars of my theme, and need to select different category for each widget.

    waiting for your response
    Thanks

    1. AJ Clarke | WPExplorer says:

      Have a look at the tax_query parameter that will help you update the code so you can alter based on different categories.

      Admin
  12. Asi says:

    Thank you AJ. but I do not know any thing about writing php and wordpress codes. I really would be thankful if anyone could help.
    It is a long time I hope I could add a little changes to this plugin.

  13. Ivan says:

    Great plugin. How can I align the products horizontally? Thanks!

    1. AJ Clarke | WPExplorer says:

      Can’t you do this via CSS? Its going to depends a lot on your theme and layout.

      Admin
  14. romymk says:

    Thanks for the plugin. How do I turn this into ‘Most viewed products’?

    1. Remi says:

      To do so you need to add a post meta field that count product views, and then sort by this custom field in the loop.

      Author
  15. sadiqur rahman says:

    I add your code to functions.php of my theme and use the shortcode in desired page but i is not working

    1. AJ Clarke | WPExplorer says:

      Sorry to hear that…maybe double check your code? Do you get any error notices with Debug enabled?

      Admin
  16. soo smart says:

    This is what my client is asking for – ‘recently viewed products’ as opposed to ‘related products’. I have copied your code into a php file.
    Questions –
    What do I save it as? “recently-viewed.php”?
    Where do I put it? In the Woo Commerce folder? In the plugins folder?
    Someone put the code in the Functions file… that sounds a bit weird – wouldn’t do that.

    1. AJ Clarke | WPExplorer says:

      You should be creating a plugin. Just make an empty folder, add a php file in it and then paste the code into the PHP file. Then upload it to your site’s plugins directory.

      Admin
  17. David says:

    Hi, How can I add “Add to cart” button ? Thanks.

    1. AJ Clarke | WPExplorer says:

      There might be a better way to do it, but I do know there is a a shortcode available – [add_to_cart_url id=”PUT ID HERE”] – so you could use the shortcode in your function with do_shortcode() to create an add to cart button.

      Admin

Sorry, comments are now closed.