Tuesday 27 December 2022

Custom Wordpress Infinite Loading Scroll With Ajax

To create an infinite scrolling effect in WordPress using Ajax, you will need to follow these steps:

  1. Create a new page template in your WordPress theme. This template will be used to display the posts in the infinite scroll.
  2. In the template, create a div element with a unique ID that will be used to hold the posts as they are loaded.
  3. Enqueue the WordPress Ajax library in your functions.php file.
  4. Write a function to handle the Ajax request and return the posts to be displayed.
  5. Bind the function to the 'wp_ajax_nopriv_' and 'wp_ajax_' actions, depending on whether the user is logged in or not.
  6. In the template, use jQuery to bind a scroll event to the window object. When the user scrolls to the bottom of the page, make an Ajax request to load more posts.
  7. In the Ajax success callback function, append the new posts to the div element created in step 2.

Here is some sample code to get you started: 


// Enqueue the WordPress Ajax library

wp_enqueue_script('ajax-script', get_template_directory_uri() . '/js/ajax.js', array('jquery'));


// Localize the script with the ajax_url variable

wp_localize_script('ajax-script', 'ajax_url', admin_url('admin-ajax.php'));


// Add the action to handle the Ajax request

add_action('wp_ajax_nopriv_load_posts', 'load_posts');

add_action('wp_ajax_load_posts', 'load_posts');


// The function to handle the Ajax request

function load_posts() {

  // Query for the posts

  $posts = new WP_Query(array(

    'post_type' => 'post',

    'posts_per_page' => 5,

    'paged' => $_POST['page']

  ));


  // Loop through the posts and build the HTML

  if ($posts->have_posts()) {

    while ($posts->have_posts()) {

      $posts->the_post();

      // Build the post HTML here

    }

  }


  // Reset the post data

  wp_reset_postdata();


  // Return the HTML

  echo $html;


  // Exit to prevent the WordPress template from loading

  exit;

}


 

// Bind the scroll event to the window object

jQuery(window).scroll(function() {

  // If we're at the bottom of the page

  if (jQuery(window).scrollTop() == jQuery(document).height() - jQuery(window).height()) {

    // Make the Ajax request

    jQuery.post(ajax_url, {

      action: 'load_posts',

      page: page

    }, function(response) {

      // Append the new posts to the div element

      jQuery('#posts').append(response);

      // Increment the page number

      page++;

    });

  }

});

I hope this helps! Let me know if you have any questions.

No comments:

Post a Comment

Popular Post