Coder's Blog Book

“How to Add a ‘Load More Related Products’ Button Using Ajax in WooCommerce”

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

To add a “Load More Related Products” button using Ajax on the WooCommerce single product page, you can use JavaScript to handle the Ajax request and update the product list dynamically. Below are the steps to achieve this:

Step 1: Create a Custom JavaScript File

Create a new JavaScript file in your theme’s folder or a custom plugin. Name it something like custom-ajax-related-products.js and add the following code:

(function ($) {
  // Function to handle the "Load More" button click
  function handleLoadMoreClick() {
    $(document).on('click', '#load-more-related-products', function (e) {
      e.preventDefault();
  var $this = $(this);
  var page = $this.data('page');

  var data = {
    action: 'custom_load_more_related_products',
    product_id: $this.data('product-id'),
    page: page,
  };

  // Send the AJAX request
  $.ajax({
    type: 'POST',
    url: wc_add_to_cart_params.ajax_url,
    data: data,
    beforeSend: function () {
      $this.addClass('loading');
    },
    success: function (response) {
      if (response) {
        // Append the loaded products to the container
        $('#related-products').append(response);

        // Update the data-page attribute
        $this.data('page', page + 1);

        // Remove loading class
        $this.removeClass('loading');

        // Hide the "Load More" button if no more products to load
        if (response.trim() === '') {
          $this.remove();
        }
      }
    },
  });
});
}

$(document).ready(function () {
handleLoadMoreClick();
});
})(jQuery);

Step 2: Enqueue the Custom JavaScript File

Next, you need to enqueue the custom JavaScript file on the WooCommerce single product page. Add the following code to your theme’s functions.php file or a custom plugin:

function custom_enqueue_ajax_related_products_script() {
  if (is_product()) {
    global $product;
    wp_enqueue_script('custom-ajax-related-products', get_stylesheet_directory_uri() . '/custom-ajax-related-products.js', array('jquery'), '1.0', true);
    wp_localize_script(
      'custom-ajax-related-products',
      'custom_ajax_related_products',
      array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'product_id' => $product->get_id(),
        'page' => 2, // Set the initial page to 2 (assuming you already have 1 page of related products loaded on the single product page)
      )
    );
  }
}
add_action('wp_enqueue_scripts', 'custom_enqueue_ajax_related_products_script');

Step 3: Create AJAX Handler for Loading Related Products

Create the AJAX handler function in your theme’s functions.php file or a custom plugin to handle the Ajax request and load related products. Add the following code:

function custom_load_more_related_products() {
  check_ajax_referer('custom_ajax_related_products', 'security');
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;

// Get related products
$related_posts_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => 4, // Adjust the number of products per page here
'orderby' => 'rand',
'post__not_in' => array($product_id),
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN',
),
),
);

$related_products = new WP_Query($related_posts_args);

if ($related_products->have_posts()) {
ob_start();

while ($related_products->have_posts()) {
  $related_products->the_post();
  wc_get_template_part('content', 'product');
}

wp_reset_postdata();

$response = ob_get_clean();

echo $response;
}

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: Modify the Single Product Template

Finally, make sure the single product template (single-product.php) contains a container to display the related products. Add the following code inside the main product container:

<div id="related-products" class="related-products">
  <?php
  // Output the first set of related products (this will be handled by the standard WooCommerce related products query)
  wc_get_template('single-product/related.php');
  ?>
</div>

Step 5: Save Changes and Test

Save the changes to your functions.php file or custom plugin. Now, when a user clicks the “Load More Related Products” button on the WooCommerce single product page, more related products will be loaded via Ajax.

Please note that this example assumes you are using the default WooCommerce related products query and template. If you have a custom query or template for related products, you may need to adjust the code accordingly. Additionally, you can customize the number of products loaded per page and the related products query as needed.

Always test the functionality thoroughly to ensure it works as expected before implementing it on a live site.

Share This On :

Leave a Comment

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