如何应用更多加载以在WordPress模板中获取自定义帖子

时间:2019-07-02 05:33:43

标签: javascript php jquery ajax wordpress

在我的网站上,我使用get posts获取自定义帖子类型的帖子。但是一次获取所有帖子,但是在我的模板中,我想每剩余页面显示x个帖子,我想使用“加载更多”按钮进行加载

       <?php 

         $id = url_to_postid( $current_url );
         $queried_post = get_post($id); 
         $post_slug = $queried_post->post_name;

         $page_number = (get_query_var('paged')) ? 
              get_query_var('paged') : 1;
           $page_link =  get_pagenum_link(9999999999);
           $term = get_term_by('slug', $post_slug, 
                     'tax_business_listing'); 
           $cat_term_id = $term->term_id;
               $args = array(

                'posts_per_page' =>3,
                'paged'=>$page_number,
                'order'            => 'ASC',
                'post_type'        => 'business',
                'post_status'      => 'publish',
                'offset'           =>  0,
                'orderby'          => 'ASC',
                 'tax_query' => array(
        array(
            'taxonomy' => 'tax_business_listing',
            'field' => 'term_id',
            'terms' => $cat_term_id,
        )
    ),
             ); 

         $posts =   get_posts( $args );
          $loop = new WP_Query( $args );
          $count = !empty($loop->posts)?count($loop->posts):0;

          $max_page = $loop->max_num_pages;

          $i=0;
         if(!empty($posts)){
         foreach ($posts as $post): 
          $i++;
          $postName = $post->post_title;
          $exp = $post->post_excerpt;
          $thumb_id = get_post_thumbnail_id();
          $thumb_url_array = wp_get_attachment_image_src($thumb_id, 
                               'thumbnail-size', true);
             $thumb_url = $thumb_url_array[0];

             ?>

            <div class="col-12 col-md-6 col-xl-4 p-0 Floor-Plans-sec">
              <div class="card flex-row flex-wrap">
                    <a href="<?=get_permalink($post->ID)?>" 
                        class="floor-hov"><i class="la la-plus"></i> 
                     </a>
                <div class="card-header border-0">
                       <img class="Floor-Plans-img" src="<?=$thumb_url? 
                         >" alt="floor img"> 
                </div>
                <div class="card-block px-2 pl-3">
                  <h4 class="card-title">Residency <?=$i?></h4>
                  <?=$exp?>
                 </div>
               </div>
            </div>
             <?php  endforeach; 
      }   ?>
          <!--load more starts here -->
       <div class="pull-right btnLoadMore">
           <div class="pull-right event-more">
             <a href="javascript:void(0)" id="load-more" 
                   onclick="loadMoreFun();" data-pagenumber="<?php 
                   echo $page_number; ?>" data-maxpage="<?php echo 
                   $max_page; ?>" data-pagelink="<?php echo 
                   $page_link; ?>">
                 <button type="button" class="btn btn-secondary pull- 
                     right">Load More</button>
             </a>
           </div>
       </div>

<script>
  function loadMoreFun() {
       var next_page = jQuery('#load-more').data("pagenumber");
       var max_page = jQuery('#load-more').data("maxpage");
       var next_page_url = jQuery('#load-more').data("pagelink");
       var $load_more_btn = jQuery(this);
       var request_data = jQuery(this).attr('pagenumber');
       next_page++;
       jQuery('#load-more').data('pagenumber',next_page);
       var next_link = next_page_url.replace(/\d+(\/)?$/, next_page + 
       '$1');
        if(next_page <= max_page) {
 var post_type = 'business'; 
  $.ajax({
    type : 'POST',
    url : next_link,
      cache: false,
      beforeSend: function(){
          jQuery('.loading-img').show();
      },
      complete: function(){
          jQuery('.loading-img').hide();
      },        
  success: function(response)  {
        if (jQuery(response).find('#Floor-Plans')){
          var newElems = jQuery(response).find('.Floor-Plans- 
              sec').html();
          console.log(newElems);
          jQuery('.Floor-Plans-sec').append(newElems);
          if(next_page == max_page){
          jQuery('#load-more').text('No More Floor Plans Available');
          }
        } else{

        }
       }
     });
   }
  }
  </script>

通过包含上面的代码,我在单击“加载更多”按钮后获得了3次第一篇帖子。我想加载剩余的帖子。请帮助我获得预期的结果。任何帮助表示感谢。.

2 个答案:

答案 0 :(得分:1)

您的代码中可能存在问题,请尝试以下代码。请根据您的代码更改条件,并检查其是否有效。

您的template.php

<div id="ajax-posts" class="row">
<?php get_header(); ?>
    <?php
        $args = array(
                'post_type' => 'business',
                'paged'    => 1,
        );
        $loop = new WP_Query($args);
        while ($loop->have_posts()) : $loop->the_post();
    ?>

     <div class="content">
            <h1><?php the_title(); ?></h1>
            <p><?php the_content(); ?></p>
     </div>

     <?php
            endwhile;
    wp_reset_postdata();
     ?>
</div>
 <p class="para"></p>
<button id="more_posts">Load More</button>

script.js

var pageNumber = 2;
jQuery(function($) {
$('body').on('click', '#more_posts', function load_posts(){
    var str = '&pageNumber=' + pageNumber + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $(".para").text("No More Posts");
                $("#more_posts").attr("disabled",true);
            }
            pageNumber++;
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
});

});

functions.php

<?php
add_action('wp_enqueue_scripts', 'myscripts');
function myscripts() { 
wp_register_script('functions', get_template_directory_uri() .'/script.js');
wp_localize_script( 'functions', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
 wp_enqueue_script('functions');
}
if (isset($_REQUEST['posts_per_page'])) {
$pageCount = $_REQUEST['posts_per_page'];
$wp_query->set("posts_per_page", $pageCount);
$wp_query->get_posts();
}
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
function more_post_ajax(){
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$args = array(
    'post_type' => 'competition',
    'paged'    => $page,
);
$loop = new WP_Query($args);
if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
    ?>
        <h2><?php the_title() ?></h2>
        <?php the_excerpt() ?>
<?php
endwhile;
endif;
wp_reset_postdata();
}
?>

答案 1 :(得分:0)

对于最简单,最简单的解决方案,我建议您使用任何第三方插件。此外,此插件将允许您根据需要创建结构。 https://wordpress.org/plugins/ajax-load-more-anything/ 如果您不想使用此插件,则可以使用此插件的代码。