WP AJAX php code

Published
2023-01-10
浏览次数 :  13

//function 
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 = $_REQUEST['current_page'] + 1;
  $query = new WP_Query(
    array(
      'posts_per_page' => 8,
      'paged' => $next_page,

    )
  );
  if($query->have_posts()) {
    ob_start();
    while($query->have_posts()) {
      $query->the_post();
      get_template_part('template-parts/content');
    }
    wp_send_json_success(ob_get_clean()); 

  } else {
    wp_send_json_error('No More Posts!'); 
  }


  var_dump($_REQUEST);

  die;
}

//page code 
<div class="recommend_list mod_list">
          <?php  $query = new WP_Query(
              array(
                'post_type' => 'post',
                'posts_per_page'  => 8,
                'ignore_sticky_posts'  => true,
              )
            ); ?> 
          
          <ul class="article-list posts-list" id="post-list" data-page="<?=get_query_var('paged') ? get_query_var('paged') : '1'?>" data-max="<?=$query->max_num_pages?>">
            <li class="clear">
              <div class="cat_head">
                <h1 class="page-title">Load more button test</h1>
                
              </div>
            </li>
            <?php
            while ($query->have_posts()) {
            $query->the_post(); get_template_part('template-parts/content'); ?>

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