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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

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 PHP snippets at the bottom of your child theme functions.php file and CSS at the bottom of its style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my guide "Should I Add Custom Code Via WP Editor, FTP or Code Snippets?" and my video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything went as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting.

If you think this code saved you time & money, feel free to join 17,000+ WooCommerce Weekly subscribers for blog post updates and 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance!

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

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