WooCommerce: “Load More Related Products” Ajax Button @ Single Product Page

As you know, the WooCommerce Single Product Page displays a set amount of related products (usually 4). But despite the fact that you can customize the number of related products via code, there is no setting that allows you to have a “LOAD MORE” button instead.

My goal is therefore to show as many Related Products as the user wants without reloading the page, so that they can find out more potential matches and increase the chances to place an order.

I must say this took me the whole morning and it’s not yet finished. There are two small bugs: (1) the “Load More” button does not hide once there are no more related products and (2) once the current product’s related products are finished (so, after clicking on the load more button 1 or more times), the Ajax keeps showing the last related product as opposed to show none. Feel free to contribute if you wish to help!

Having said that, let’s see how to implement an Ajax “load more” feature. You can also reuse this on different projects (e.g. “load more blog posts”), because once you get to understand how Ajax works then you can do lots of cool stuff without refreshing the page.

Enjoy!

Let’s load more related products without refreshing the page! Click the button, and see the magic happen.

PHP Snippet: “Load More” Ajax Button @ WooCommerce Single Product Page Related Products

I’ve tried to comment each part of the snippet, so that you can learn a thing or two about Ajax.

Note: you probably need to also use some code to always show the same set of Related Products on load, otherwise the “Load More” function may show totally wrong results upon click.

/**
 * @snippet       Related Products Load More Button
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 7
 * @community     https://businessbloomer.com/club/
 */

add_filter( 'woocommerce_product_loop_end', 'bbloomer_related_products_load_more_button' );
 
function bbloomer_related_products_load_more_button( $html ) {

   // ONLY TARGET THE RELATED PRODUCTS LOOP
	if ( wc_get_loop_prop( 'name' ) === 'related' ) {
   
      // SHOW BUTTON
		$html .= '<a class="button loadmore">Load More Related Products</a>';

      // TRIGGER AJAX 'loadmore' ACTION ON CLICK
      // AND APPEND MORE RELATED PRODUCTS 
		wc_enqueue_js( "
			var page = 2;
			var ajaxurl = '" . admin_url( 'admin-ajax.php' ) . "';
			$('body').on('click', '.loadmore', function(evt) {
				var data = {
					'action': 'loadmore',
					'page': page,
					'product_id': " . get_queried_object_id() . ",
				};
				$.post(ajaxurl, data, function(response) {
					if(response != '') {
						$('.related .products ').append(response);
						page++;
					}
				});
			});
		" );
	}
	return $html;
}

// DEFINE WHAT HAPPENS WHEN 'loadmore' ACTION TRIGGERS
add_action( 'wp_ajax_nopriv_loadmore', 'bbloomer_related_products_load_more_event' );
add_action( 'wp_ajax_loadmore', 'bbloomer_related_products_load_more_event' );

function bbloomer_related_products_load_more_event() {

   // GET PARAMETERS FROM POSTED DATA
	$paged = $_POST['page'];
	$product_id = $_POST['product_id'];

   // DEFINE USEFUL QUERY ARGS:
   // 1. CURRENT PRODUCT
	$product = wc_get_product( $product_id );

   // 2. PAGINATION AND SORTING
	$args = array(
		'posts_per_page' => 3,
		'paged' => $paged,
		'orderby' => 'id',
		'order' => 'desc',
	);

   // 3. IDS TO EXCLUDE: ON LOAD MORE, WE DONT WANT THE FIRST 3 RELATED PRODUCTS AGAIN
   // SO WE APPLY AN OFFSET TO GET THE "NEXT 3" PRODUCTS
	$exclude = array_slice( array_map( 'absint', array_values( wc_get_related_products( $product->get_id(), -1 ) ) ), 0 , $args['posts_per_page'] * ( $paged - 1 ) );

   // LETS CALCULATE AND SORT RELATED PRODUCTS
	$related_products = array_filter( array_map( 'wc_get_product', wc_get_related_products( $product->get_id(), $args['posts_per_page'], $exclude + $product->get_upsell_ids() ) ), 'wc_products_array_filter_visible' );
	$related_products = wc_products_array_orderby( $related_products, $args['orderby'], $args['order'] );

   // LETS DISPLAY THEM
	foreach ( $related_products as $related_product ) {
		$post_object = get_post( $related_product->get_id() );
		setup_postdata( $GLOBALS['post'] =& $post_object );
		wc_get_template_part( 'content', 'product' );
	}	
	wp_die();

}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: How to Enable Product Filters (i.e. “Ajax Filters”)?
    If your WooCommerce store has many products, online customers might get easily lost. There might be way too many pages to visit (“product pagination”) before finding the product they’re looking for. Needless to say, this is a huge loss for your business. Possibly, they’ll never come back. If you shop on popular ecommerce websites such as […]
  • WooCommerce: Why & How to Disable Ajax Cart Fragments
    If you’re here it’s because your WooCommerce website is slow and you’re wondering why the “/?wc-ajax=get_refreshed_fragments” URL generates delays and server loads (spikes). Besides, there is too much online literature about WooCommerce Ajax Cart Fragments (including specific plugins and performance plugin options), and you want to learn quickly what they are before understanding if and […]
  • WooCommerce: Custom Related Products
    WooCommerce picks related products on the Single Product Page based on product categories and/or product tags. Related products are very important to the shopping experience, and sometimes this is not enough – what if you want to automatically show certain products based on different criteria? So, here’s a quick snippet to e.g. get related products […]
  • WooCommerce: Ajax Add to Cart Quantity @ Shop
    As you know, you can tick the “Enable AJAX add to cart buttons on archives” checkbox in the WooCommerce settings in order to add products to cart from the Shop / Category / Tag / loop pages without refreshing the page. This is great for certain businesses, especially those who sell in bulk and where […]
  • WooCommerce: Related Products in a Custom Tab @ Single Product Page
    This is a simple snippet that will allow you to move the Related Products from below the tabs to inside the single product tabs, in a brand new tab.

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

2 thoughts on “WooCommerce: “Load More Related Products” Ajax Button @ Single Product Page

  1. This post was very helpful to me.
    Keep up the good work!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *