AJAX “Load More” Related Products in WooCommerce
Want to improve user experience on your WooCommerce product page? Here’s how to dynamically load more related products using AJAX in a few steps.
Step 1: Create a JavaScript File
First, create a JavaScript file named custom-ajax-related-products.js and add the following jQuery code:
(function ($) {
$(document).on('click', '#load-more-related-products', function (e) {
e.preventDefault();
var $btn = $(this);
var page = $btn.data('page');
var data = {
action: 'custom_load_more_related_products',
product_id: $btn.data('product-id'),
page: page,
};
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.ajax_url,
data: data,
beforeSend: function () {
$btn.addClass('loading');
},
success: function (res) {
if (res) {
$('#related-products').append(res);
$btn.data('page', page + 1).removeClass('loading');
if (res.trim() === '') $btn.remove();
}
},
});
});
})(jQuery);
Step 2: Enqueue the Script
Enqueue your script in the functions.php:
function enqueue_custom_ajax_script() {
if (is_product()) {
global $product;
wp_enqueue_script('custom-ajax-related-products', get_stylesheet_directory_uri() . '/custom-ajax-related-products.js', ['jquery'], '1.0', true);
wp_localize_script('custom-ajax-related-products', 'custom_ajax_related_products', [
'ajax_url' => admin_url('admin-ajax.php'),
'product_id' => $product->get_id(),
'page' => 2,
]);
}
}
add_action('wp_enqueue_scripts', 'enqueue_custom_ajax_script');
Step 3: Handle the AJAX Request
Add this to your theme or plugin:
function custom_load_more_related_products() {
$product_id = intval($_POST['product_id'] ?? 0);
$page = intval($_POST['page'] ?? 1);
$args = [
'post_type' => 'product',
'posts_per_page' => 4,
'post__not_in' => [$product_id],
'orderby' => 'rand',
'post_status' => 'publish',
];
$query = new WP_Query($args);
if ($query->have_posts()) {
ob_start();
while ($query->have_posts()) {
$query->the_post();
wc_get_template_part('content', 'product');
}
wp_reset_postdata();
echo ob_get_clean();
}
wp_die();
}
add_action('wp_ajax_custom_load_more_related_products', 'custom_load_more_related_products');
add_action('wp_ajax_nopriv_custom_load_more_related_products', 'custom_load_more_related_products');
Step 4: Update Template
Ensure your single-product.php has this markup:
<div id="related-products">
<?php wc_get_template('single-product/related.php'); ?>
</div>
Step 5: Test the Button
Save everything and test the button on your single product page. The related products should load seamlessly with AJAX.
