ajax-inifit-load写法

Published
2022-04-23
浏览次数 :  171

js部分

'use strict';
jQuery(document).ready(($) => {

  const button = $('.load-more-btn');
  const ajaxurl = custom_rest_api.ajax_url
  const post_list = $('#posts-list');

  button.on('click',(e) => {

    let current_page = post_list[0].dataset.page;
    let max_page = post_list[0].dataset.max;
    
    
    let postdata = "action=load_more_posts&current_page="+current_page;

    $.post(ajaxurl,postdata,(response) => {
      post_list.append(response.data);

      //将无限加载当前保存的页数地址推送到url栏确保刷新不会变换
      window.history.pushState('','','/fakenews');

      if (current_page == max_page) {
        $('.load-more-btn').parent().remove();
      }

      $('#posts-list')[0].dataset.page++;
    });

  });

});

php部分

//ajax call 无限加载按钮
add_action('wp_ajax_nopriv_load_more_posts','load_more_posts');
add_action('wp_ajax_load_more_posts','load_more_posts');

function load_more_posts() {
	$next_page = $_POST['current_page'] + 1;
	$query = new WP_Query(array(
		'post_type' => 'event',
		'posts_per_page' => 3,
		'paged' => $next_page

	));

	if ($query->have_posts()) {
		//start object buffer
		ob_start();
		while($query->have_posts()) {
			$query->the_post(); ?>
			<div class="card card-horizontal card-hover mb-4 px-sm-5 py-sm-0 py-3">
              <div class="card-header flex-shrink-0 my-sm-4 ms-sm-n2 py-sm-2 px-sm-0 border-0">
                <div class="d-flex">
                  <?php
                    $datetime =  get_post_meta( get_the_ID(), 'event_date_field',true );
                    $time = new DateTime($datetime);

                    //var_dump($time->format('F')); ?>
                  <span class="display-4 mb-0 text-primary" style="font-size: 3rem;"><?php echo $time->format('d') ?></span>
                  <div class="ms-3 ps-1">
                    
                    <h6 class="h5 mb-1"><?php echo $time->format('F') ?></h6>
                    <span class="text-muted"><?php echo $time->format('g:i') ?></span>
                  </div>
                </div>
              </div>
              <div class="card-body m-sm-4 py-sm-2 py-0 px-sm-3">
                <h3 class="h5 mb-sm-1 mb-2">
                  <a href="event-single.html" class="nav-link"><?php  the_title(); ?></a>
                </h3>
                <span class="text-muted"><?php echo get_post_meta( get_the_ID(),'event_name_field',true ); ?></span>
              </div>
              <div class="card-footer flex-shrink-0 my-sm-4 mt-5 me-sm-n2 py-sm-2 px-sm-0 border-0">
                <a href="<?php  the_permalink() ?>" class="btn btn-outline-primary btn-hover-shadow d-sm-inline-block d-block">View more</a>
              </div>
            </div>

			<?php 
		}
		//返回请求的所有string 
		wp_send_json_success(ob_get_clean());
		// code...
	} else {
		wp_send_json_error('No more posts');
	}

}

  • 标签1
  • 标签1
  • 标签1
Top