php – Loading posts by clicking a button on WordPress (AJAX)

Question:

Good day. I have a WP site. I am trying to do AJAX loading of posts. I understand that the topic is hackneyed, but nowhere was it possible to find a single solution that can somehow be adapted to my case.

The "news" section displays records (2 items). There is a "Read more" button under this block. By clicking on it, two more news should appear. Etc. I have no pagination, nothing by which it would be possible to understand which page you are on. I tried to write a solution myself, but it doesn't work (I suspect something is wrong with PHP and getting data in AJAX, but I can't tell what exactly).

What exactly should AJAX request and PHP serve? Thank you.

Post output structure:

<div class="row">       

            <?php if ( have_posts() ) :  while ( have_posts() ) : the_post(); ?>
              <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
              <div class="news-date">
                <?php the_time($format = 'j F Y'); ?>
              </div>
              <div>
                <h3><?php the_title(); ?></h3>
                <p><?php the_content(); ?></p>
              </div>
            </div>
            <?php endwhile; ?>
            <?php endif; ?>

          </div>

          <div class="more-link"><a href="#">Read more></a>
              </div>

JS

$(function() {


    var posts = 2;
    var posts_offset = 0;

    $("#load-post").click(function() {


                $.ajax({
                type: "GET",
                url: "/wordpress/wp-admin/themes/my_theme/load-posts.php", 
                dataType: 'html',
                data: ({ <?php $posts ?>}),
                success: function(data){
                    $('.news').append(data);
                    posts_offset += 2;

                }
            });
        }

    });
});

PHP

if (isset($_GET['posts_offset']))
{
  $posts_offset = $_GET['posts_offset'];
}
$posts = get_posts( array(
  'numberposts'     => 2,
  'offset'          => $posts_offset
) );

!! UPD !!

Corrected the code, now the following happens: the code from the PHP file is appended to the end of .news, and not additional posts.

Js

    $(function () {

  var posts = 2;
  var posts_offset = 0;

  $("#load-post").click(function (e) {
    e.preventDefault();

    $.ajax({
      type: "POST",
      url: "/wp-content/themes/1cka/load-posts.php",
      dataType: 'html',
      data: {
        posts_offset: posts_offset
      },
      success: function (data) {
        $('.news').append(data);
        posts_offset += 2;

      }
    });
  })
});

PHP

<?php require_once("header.php"); ?>
<?php
if (isset($_GET['posts_offset']))
{
  $posts_offset = $_GET['posts_offset'];
}

global $post;

// записываем $post во временную переменную $tmp_post
$tmp_post = $post;
$args = array( 'posts_per_page' => 2, 'offset'=> $posts_offset );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
    <?php if ( have_posts() ) :  while ( have_posts() ) : the_post(); ?>
            echo  '<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 news-item">
              <div class="news-date">
                <?php the_time($format = 'j F Y'); ?>
              </div>
              <div>
                <h3><?php the_title(); ?></h3>
                <p><?php the_content(); ?></p>
              </div>
            </div>'
            <?php endwhile; ?>
            <?php endif; ?>
<?php endforeach; 

$post = $tmp_post;

?>

Answer:

A very good and understandable example for organizing loading when scrolling and by clicking: https://www.billerickson.net/infinite-scroll-in-wordpress/ True, in JS, you also need to check whether such a class exists on the page, so as not gave errors in the console

if( $('.post-box-list').length ) { 
Код тут
}
Scroll to Top