如何通过AJAX“加载更多”帖子?

时间:2019-02-14 作者:Robert Andrews

关于分类法{name}。php模板用于我的“组织”分类法,我目前显示的帖子数量有限,按分类法的每个术语“格式”分组。

如果可用帖子的数量超过了可显示的数量,我现在想启用基于AJAX的加载更多帖子。

我已经关注了无数关于这个主题的教程和StackExchange问题,但有些东西仍然没有点击。例如,我实现了Misha Rudrastyh\'s "Load More" button, 但代码不会加载任何帖子。我迷路了,快要放弃了。

我有一个帖子块,上面有这样一个“更多”链接,准备好了,等待着。。。

enter image description here

这对应于一个分类法“组织”术语的“格式”分类法术语“执行”的帖子。以下是分类组织的相关部分。php,包含我的查询。。。

 <?php


 // This will output posts in blocks for each "Format" taxonomy term.
 // But we also want to use this loop to output posts *without* a "Format" taxonomy term.


 $formats = array("interview","executive","analyst","oped","","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");

 foreach ($formats as $format) {

      // Term of the slug above
      $format_term = get_term_by(\'slug\', $format, "format");

      // Formulate the secondary tax_query for "format" with some conditionality
      /* *********************************** */
      /*           Posts by Format           */
      /* *********************************** */
      if (!empty($format)) {
           $posts_per_page = 8;
           $tax_q_format_array = array(
                \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                \'field\'    => \'slug\',
                \'terms\'    => $format_term->slug,
                \'include_children\' => false
           );
           // Oh, and set a title for output below
           $section_title = $format_term->name;
      /* *********************************** */
      /*         Format without Format       */
      /* *********************************** */
      } elseif (empty($format)) {
           $posts_per_page = 12;
           $tax_q_format_array = array(
                \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                \'operator\' => \'NOT EXISTS\', // or \'EXISTS\'
           );
           // Oh, and set a title for output below
           $section_title = \'Reporting\';
      }

      // Query posts
      $paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
      $args = array(
        // pagination
        // \'nopaging\' => false,
        \'posts_per_page\' => $posts_per_page,
        // \'offset\' => \'4\',
        // \'paged\' => $paged,
        // posts
        \'post_type\' => array( \'article\', \'viewpoint\' ),
        // order
        \'orderby\' => \'date\',
        \'order\'   => \'DESC\',
        // taxonomy
        \'tax_query\' => array(
          array(
            \'taxonomy\' => \'company\', // from above, whatever this taxonomy is, eg. \'source\'
            \'field\'    => \'slug\',
            \'terms\'    => $organisation->slug,
            \'include_children\' => false
          ),
          $tax_q_format_array
       ),
      );

      // the query
      $posts_org = new WP_Query($args);



      if ( $posts_org->have_posts() ) { ?>

           <h5 class="mt-0 pt-2 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>

           <div class="row pb-3">
           <?php
           while( $posts_org->have_posts() ) {
                $posts_org->the_post();
                get_template_part(\'partials/loops/col\', \'vertical\');
           }
           if ($posts_org->found_posts > $posts_per_page) {
                echo \'<p class="text-secondary pl-3 pb-0 load_more" style="opacity: 0.6"><i class="fas fa-plus-circle"></i> More</p>\';
           }
           echo \'</div>\';
           wp_reset_postdata(); // reset the query

      } else {
           // echo \'<div class="col"><p>\'.__(\'Sorry, no posts matched your criteria.\').\'</p></div>\';
      } // end if have_posts


 }










 ?>
这是使用的包含文件get_template_part 要输出帖子项目缩略图和链接。。。

    <?php
    // Get fallback image if needed
    @require(dirname(__FILE__).\'/../source_thumbnail_fallback.php\');
    // @ Suppress "Notices" generated when post has no source set (ie no source at array position [0])
    ?>


    <div class="col-sm-6 col-md-4 col-lg-3 col-xl-2 post-item overlay-bg <?php echo $display_class; ?>">
            <a href="<?php the_field( \'source_url\' ); ?>" class="text-dark" target="_blank">
                    <img src="http://www.myserver.com/to/image/location/<?php echo $source_image_url; ?>" class="img-fluid rounded mb-2">
                    <p><?php the_title(); ?></p>
                    <?php
                    //Do something if a specific array value exists within a post
                    $format_terms = wp_get_post_terms($post->ID, \'format\', array("fields" => "all"));
                                    // foreach($format_terms as $format_single) { ?>
                        <span class="badge <?php get_format_badge_colour_class($format_terms[0]->term_id); ?> font-weight-normal mr-2 overlay-content"><?php echo $format_terms[0]->name; ?></span>
                                    <?php // } ?>
            </a>
    </div>
从教程和问题中,我发现这个过程似乎是。。。

注册/排队/本地化包含相关代码的Javascript文件,并从PHP函数向其传递参数。php函数中的某种WordPress AJAX处理程序。php哪个做WP\\u查询更多帖子

仅供参考,我的自建主题基于Bootstrap,到目前为止,我已经取消了WordPress内置的注册jquery, 替换为enqueuing Bootstrap的建议https://code.jquery.com/jquery-3.3.1.slim.min.jsjQuery. 我不确定哪个是正确的选择,似乎这对WP\\U Ajax\\u*有影响。

我知道以前也有人问过类似的问题,但我的问题似乎是独特的,许多问题/答案似乎也涉及到独特的情况,即提供专门针对二十一五主题的答案。

更新(2019年2月15日):

我在解决这个问题上走了很长的路,结合使用了:

  • Artisans Web tutorial 对于基本概念Anti\'s suggestion 为了建立点击了多个“更多”链接中的哪个链接(有必要将唯一参数反馈给循环WP查询)

    主题模板片段:

     <?php
     $organisation = get_query_var(\'organisation\');
     $org_id_prefixed = get_query_var(\'org_id_prefixed\');
     ?>
    
    
     <?php
    
    
     /* ************************************************************************************************************** */
     /*                                                                                                                */
     /*          LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING                                        */
     /*                                                                                                                */
     /*          Outline:                                                                                             */
     /*          This will output posts in blocks for each "Format" taxonomy term.                                     */
     /*          But we also want to use this loop to output posts *without* a "Format" taxonomy term.                 */
     /*          >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/                 */
     /*                                                                                                                */
     /*          Dynamic:                                                                                              */
     /*          1. Javascript: When "More" link is clicked                                                            */
     /*          2. Send current "organisation", clicked "format" and "page" as variables to function                  */
     /*          3. PHP: Do WP query for next page of posts, return to javascript                                      */
     /*          4. Javascript: Append results to the clicked container                                                */
     /*                                                                                                                */
     /*          Dynamic method:                                                                                       */
     /*          $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know:           */
     /*          a) Which "Load more" link was clicked                                                                 */
     /*          b) Which box to return new output to                                                                  */
     /*          >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300        */
     /*                                                                                                                */
     /* ************************************************************************************************************** */
    
    
     // Specify which "Format" terms we want to display post blocks for
     // ("reporting" here is a wildcard, used to accommodate posts without a "Format" term set)
     $formats = array("interview","executive","analyst","oped","reporting","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
    
     // For each of them,
     foreach ($formats as $format) {
    
          // 1. Get actual term of the slug above
          $format_term = get_term_by(\'slug\', $format, "format");
    
          // 2. Formulate the secondary tax_query for "format" with some conditionality
          /* *********************************** */
          /*           Posts by Format?          */
          /* *********************************** */
          if ($format!="reporting") {
               // $posts_per_page = 8;
               $tax_q_format_array = array(
                    \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                    \'field\'    => \'slug\',
                    \'terms\'    => $format_term->slug,
                    \'include_children\' => false
               );
               // Oh, and set a title for output below
               $section_title = $format_term->name;
          /* *********************************** */
          /*         Format without Format?      */
          /* *********************************** */
          } elseif ($format=="reporting") {
               // $posts_per_page = 12;
               $tax_q_format_array = array(
                    \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                    \'operator\' => \'NOT EXISTS\', // or \'EXISTS\'
               );
               // Oh, and set a title for output below
               $section_title = \'Reporting\';
          }
    
          // 3. Set query arguments
          $paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
          $args = array(
            // pagination
            // \'nopaging\' => false,
            \'posts_per_page\' => \'8\', // $posts_per_page,
            // \'offset\' => \'4\',
            \'paged\' => $paged,
            // posts
            \'post_type\' => array( \'article\', \'viewpoint\' ),
            // order
            \'orderby\' => \'date\',
            \'order\'   => \'DESC\',
            // taxonomy
            \'tax_query\' => array(
              // #1 Organisation: the current one
              array(
                \'taxonomy\' => \'company\', // from above, whatever this taxonomy is, eg. \'source\'
                \'field\'    => \'slug\',
                \'terms\'    => $organisation->slug,
                \'include_children\' => false
              ),
              // #2 Format: as above
              $tax_q_format_array
            ),
          );
    
          // 4. Query for posts
          $posts_org = new WP_Query($args);
    
    
          // 5. Output
          if ( $posts_org->have_posts() ) { ?>
    
               <h5 class="mt-0 pt-4 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>
               <div class="row pb-0 my-posts" id="<?php echo $format; ?>">
               <?php
               while( $posts_org->have_posts() ) {
                    $posts_org->the_post();
                    get_template_part(\'partials/loops/col\', \'vertical\');
               }
               ?>
               </div>
               <?php
               // wp_reset_postdata(); // reset the query
    
               // "More" posts link
               if ($posts_org->found_posts > $posts_per_page) {
                    echo \'<p class="text-secondary pb-0" style="opacity: 0.6"><a href="javascript:;" class="loadmore" id="\'.$format.\'"><i class="fas fa-plus-circle"></i> <span class="moretext">More</span></a></p>\';
               }
    
          } else {
               // echo \'<div class="col"><p>\'.__(\'Sorry, no posts matched your criteria.\').\'</p></div>\';
          } // end if have_posts
    
    
     }
    
    
     ?>
    
    
    
     <script type="text/javascript">
    
     // Set starting values which to send from Javascript to WP query function...
     var ajaxurl = "<?php echo admin_url( \'admin-ajax.php\' ); ?>";
     var page = 2;                                                                // Infer page #2 to start, then increment at end
     var org_slug = "<?php echo $organisation->slug; ?>";                         // Slug of this "organisation" term
    
     jQuery(function($) {
    
          // When this selector is clicked
        $(\'body\').on(\'click\', \'.loadmore\', function() {
    
               // Get ID of clicked link (corresponds to original $format value, eg. "executive"/"reporting")
               var clicked_format = $(this).attr(\'id\');
    
               // Change link text to provide feedback
               $(\'#\'+clicked_format+\' .moretext\').text(\'Loading...\');
               $(\'#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-cog fa-spin\');
    
               // 1. Send this package of variables to WP query function
            var data = {
                \'action\': \'load_posts_by_ajax\',
                \'page\': page,
                    \'org_slug\': org_slug,
                    \'clicked_format\': clicked_format,
                \'security\': \'<?php echo wp_create_nonce("load_more_posts"); ?>\'
            };
    
               // 2. Send to query function and get results
            $.post(ajaxurl, data, function(response) {
                    // Append the returned output to this selector
                $(response).appendTo(\'div#\'+clicked_format).hide().fadeIn(2000); // was: $(\'div#\'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
                    // Change link text back to original
                    $(\'#\'+clicked_format+\' .moretext\').text(\'More\');
                    $(\'#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-plus-circle\');
                    // Increment page for next click
                page++;
            });
    
    
    
    
    
        });
    
    
    
     });
     </script>
    
    函数中的

    。php:

      // Called from org_deck2_many.php
    
      add_action(\'wp_ajax_load_posts_by_ajax\', \'load_posts_by_ajax_callback\');
      add_action(\'wp_ajax_nopriv_load_posts_by_ajax\', \'load_posts_by_ajax_callback\');
    
      function load_posts_by_ajax_callback() {
          check_ajax_referer(\'load_more_posts\', \'security\');
    
          // 1. Query values are passed from referring page, to Javascript and to this query...
          $paged = $_POST[\'page\'];                               // Passed from page: Which page we are on
          $org_slug = $_POST[\'org_slug\'];                        // Passed from page: Organisation taxonomy term slug
          $clicked_format = $_POST[\'clicked_format\'];            // ID of the clicked "More" link (corresponds to original $format value, eg. "executive"/"reporting")
          // $tax_q_format_array = $_POST[\'tax_q_format_array\']; // Passed from page: \'Format\' term-specifying part for \'tax_query\'
    
          // 2. Formulate the secondary tax_query for "format" with some conditionality
          /* *********************************** */
          /*           Posts by Format?          */
          /* *********************************** */
          if ($clicked_format!="reporting") {
               $tax_q_format_array = array(
                    \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                    \'field\'    => \'slug\',
                    \'terms\'    => $clicked_format,
                    \'include_children\' => false
               );
               // $offset = NULL;
          /* *********************************** */
          /*         Format without Format?      */
          /* *********************************** */
          } elseif ($clicked_format=="reporting") {
               $tax_q_format_array = array(
                    \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                    \'operator\' => \'NOT EXISTS\', // or \'EXISTS\'
               );
               // $offset = \'12\';      // More articles shown in "Reporting"
          }
    
          // 3. Set query arguments
          $args = array(
               // posts
              \'post_type\' => array( \'article\', \'viewpoint\' ),
              \'post_status\' => \'publish\',
              // \'offset\' => $offset,
              // pages
              \'posts_per_page\' => \'8\',
              \'paged\' => $paged,
              // taxonomy
              \'tax_query\' => array(
                // #1 Organisation: the current one
                array(
                 \'taxonomy\' => \'company\', // from above, whatever this taxonomy is, eg. \'source\'
                 \'field\'    => \'slug\',
                 \'terms\'    => $org_slug,
                 \'include_children\' => false
                ),
                // #2 Format: as above
                $tax_q_format_array
              ),
          );
    
          // 4. Query for posts
          $posts_org = new WP_Query( $args );
    
          // 5. Send results to Javascript
          if ( $posts_org->have_posts() ) :
              ?>
              <?php while ( $posts_org->have_posts() ) : $posts_org->the_post(); ?>
                  <?php get_template_part(\'partials/loops/col\', \'vertical\'); ?>
              <?php endwhile; ?>
              <?php
          endif;
    
          wp_die();
      }
    

    However, there is a remaining issue that I know about...

    在获取点击的“更多”链接的ID时,似乎存在Javascript问题clicked_format 并单击页面上的多个“更多”链接。我可以看到这一点,因为前几次“更多”单击成功,但单击其他“更多”链接可以使流程处于“加载”状态。

    我怀疑这与什么时候clicked_format 设置并销毁(或不销毁)。我试过让它不安,但没有效果。

    我是否应该考虑为此在WordPress开发或StackOverflow(Javascript)中单独提出一个具体的问题?

    http://recordit.co/AI7OjJUVmH

2 个回复
最合适的回答,由SO网友:Antti Koskinen 整理而成

您可以使用ajax在归档页面上加载更多帖子。

在“更多”链接上附加js/jquery单击事件将ajax请求发送到admin-ajax.php (使用wp_localize_script 要获取前端的ajax url),请使用页码(使用js变量跟踪)add_action( \'wp_ajax_my_action\', \'my_action\' ); 和add_action( \'wp_ajax_nopriv_my_action\', \'my_action\' ); (对于未登录的用户)。邮寄my_action 作为ajax请求的动作挂钩的一部分action 参数paged arg,在代码中注释掉了来自ajax请求的查询,例如。$_POST[\'page\']

  • 将查询到的帖子发送回前端
  • 使用js/jquery将来自ajax响应的帖子附加到dom
  • 我认为,如果使用默认jQuery版本或更新版本来加载更多帖子,那没什么大不了的。

    请看一下这里的代码示例,https://www.billerickson.net/infinite-scroll-in-wordpress/不是我的博客),以获取更详细的示例和解释。我知道代码示例比链接更受欢迎,但比尔·埃里克森编写的代码示例相当长,因此我认为更方便的做法是发布一个链接,而不是在这里复制粘贴示例。

    您还应该看看关于ajax的codex条目,它非常有用。https://codex.wordpress.org/AJAX_in_Plugins

    我只是粗略地看了一眼您发布的查询功能,但我认为大部分帖子都可以使用ajax加载更多帖子。

    <小时>

    UPDATE 15.2.2019

    如果需要确定单击了哪个“加载更多”链接/按钮,可以在js/jquery中执行此操作。

    // Html
    <div id="posts-cat-1" class="posts-section">
    // posts here
    <button id="cat-name-1" class="load-more">Load more</button>
    </div>
    
    <div id="posts-cat-2" class="posts-section">
    // posts here
    <button class="load-more" data-category="cat-name-2">Load more</button>
    </div>
    
    <div id="cat-name-3" class="posts-section">
    // posts here
    <button class="load-more">Load more</button>
    </div>
    
    // jQuery
    jQuery(\'.load-more\').on(\'click\',function(event){
    // get cat name from id
    var catName1 = jQuery(this).attr(\'id\');
    // or from data attribute
    var catName2 = jQuery(this).attr(\'data-category\'); // or .data(\'category\');
    // or from parent section, perhaps not ideal
    var catName3 = jQuery(this).closest(\'.posts-section\').attr(\'id\');
    
    // Then pass the catName to your ajax request data so you can identify which category to query in php.
    });
    
    <小时>

    UPDATE 16.2.2019

    要在没有更多帖子显示时隐藏“加载更多”按钮,可以在jquery ajax调用中添加一个简单的if-else条件。

    // 2. Send to query function and get results
    $.post(ajaxurl, data, function(response) {
    
      // Check if there\'s any content in the response.
      // I think your ajax php should return empty string when there\'s no posts to show
      if ( \'\' !== response ) {
    
        // Append the returned output to this selector
        $(response).appendTo(\'div#\'+clicked_format).hide().fadeIn(2000); // was: $(\'div#\'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
    
        // Change link text back to original
        $(\'a#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-plus-circle\'); // Icon
        $(\'a#\'+clicked_format+\' .moretext\').text(\'More\');                // Text
    
        // Increment "data-page" attribute of clicked link for next click
        // page++;
        $(\'a#\'+clicked_format).find(\'span\').data().page++
    
      } else {
    
        // This adds display:none to the button, use .remove() to remove the button completely
        $(\'a#\'+clicked_format).hide();
    
      }
    
    });
    

    SO网友:Robert Andrews

    这就是学习曲线。

    此解决方案有多个来源:

    • Artisan Web tutorial

      Javascript: In-line activate on click of "More" link.

      在我的例子中,由于使用了多个帖子块来显示,脚本必须知道单击了哪个链接。因此,我需要为post块设置一个命名区域,并相应地命名链接。

      此外,对于单击了“更多”的特定块,只增加下一页很重要。因此,我们在链接中设置了一个“数据页”属性,从第2页的默认值2开始。然后我们提取这个值并将其用作“页面”。然后我们增加这个,下次只增加这个。

      WordPress function in functions.php

      通过wp\\u ajax\\u load\\u posts\\u by\\u ajax和wp\\u ajax\\u nopriv\\u load\\u posts\\u by\\u ajax操作激发,它实际上复制了与我的模板文件中相同的wp查询设置,但巧妙地将单击链接的名称引入,以对应tax\\u查询数组中所需的分类术语值。

      Javascript: New results sent back to front-end

      新帖子将附加到posts块。然后页面会增加。

      增强欢迎使用代码或此说明。

      主题模板片段:

       <?php
       $organisation = get_query_var(\'organisation\');
       $org_id_prefixed = get_query_var(\'org_id_prefixed\');
       ?>
      
      
       <?php
      
      
       /* ************************************************************************************************************** */
       /*                                                                                                                */
       /*          LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING                                        */
       /*                                                                                                                */
       /*          Outline:                                                                                             */
       /*          This will output posts in blocks for each "Format" taxonomy term.                                     */
       /*          But we also want to use this loop to output posts *without* a "Format" taxonomy term.                 */
       /*          >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/                 */
       /*                                                                                                                */
       /*          Dynamic:                                                                                              */
       /*          1. Javascript: When "More" link is clicked                                                            */
       /*          2. Send current "organisation", clicked "format" and "page" as variables to function                  */
       /*          3. PHP: Do WP query for next page of posts, return to javascript                                      */
       /*          4. Javascript: Append results to the clicked container                                                */
       /*                                                                                                                */
       /*          Dynamic method:                                                                                       */
       /*          $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know:           */
       /*          a) Which "Load more" link was clicked                                                                 */
       /*          b) Which box to return new output to                                                                  */
       /*          c) Employs data-page attribute in link - picks up this and increments page only for this              */
       /*          >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300        */
       /*                                                                                                                */
       /* ************************************************************************************************************** */
      
      
       // Specify which "Format" terms we want to display post blocks for
       // ("reporting" here is a wildcard, used to accommodate posts without a "Format" term set)
       $formats = array("interview","executive","analyst","oped","reporting","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
      
       // For each of them,
       foreach ($formats as $format) {
      
            // 1. Get actual term of the slug above
            $format_term = get_term_by(\'slug\', $format, "format");
      
            // 2. Formulate the secondary tax_query for "format" with some conditionality
            /* *********************************** */
            /*           Posts by Format?          */
            /* *********************************** */
            if ($format!="reporting") {
                 $posts_per_page = 8;
                 $tax_q_format_array = array(
                      \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                      \'field\'    => \'slug\',
                      \'terms\'    => $format_term->slug,
                      \'include_children\' => false
                 );
                 // Oh, and set a title for output below
                 $section_title = $format_term->name;
            /* *********************************** */
            /*         Posts without Format?       */
            /* *********************************** */
            } elseif ($format=="reporting") {
                 $posts_per_page = 8;
                 $tax_q_format_array = array(
                      \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                      \'operator\' => \'NOT EXISTS\', // or \'EXISTS\'
                 );
                 // Oh, and set a title for output below
                 $section_title = \'Reporting\';
            }
      
            // 3. Set query arguments
            $paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
            $args = array(
              // pagination
              // \'nopaging\' => false,
              \'posts_per_page\' => $posts_per_page,
              // \'offset\' => \'4\',
              \'paged\' => $paged,
              // posts
              \'post_type\' => array( \'article\', \'viewpoint\' ),
              // order
              \'orderby\' => \'date\',
              \'order\'   => \'DESC\',
              // taxonomy
              \'tax_query\' => array(
                // #1 Organisation: the current one
                array(
                  \'taxonomy\' => \'company\', // from above, whatever this taxonomy is, eg. \'source\'
                  \'field\'    => \'slug\',
                  \'terms\'    => $organisation->slug,
                  \'include_children\' => false
                ),
                // #2 Format: as above
                $tax_q_format_array
              ),
            );
      
            // 4. Query for posts
            $posts_org = new WP_Query($args);
      
      
            // 5. Output
            if ( $posts_org->have_posts() ) { ?>
      
                 <h5 class="mt-0 pt-4 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $posts_org->found_posts; ?></span></h5>
                 <div class="row pb-0 my-posts" id="<?php echo $format; ?>">
                 <?php
                 while( $posts_org->have_posts() ) {
                      $posts_org->the_post();
                      get_template_part(\'partials/loops/col\', \'vertical\');
                 }
                 ?>
                 </div>
                 <?php
                 // wp_reset_postdata(); // reset the query
      
                 // "More" posts link
                 if ($posts_org->found_posts > $posts_per_page) {
                      echo \'<p class="text-secondary pb-0" style="opacity: 0.6"><a href="javascript:;" class="loadmore" id="\'.$format.\'"><i class="fas fa-plus-circle"></i> <span class="moretext" data-page="2">More</span></a></p>\';
                 }
      
            } else {
                 // echo \'<div class="col"><p>\'.__(\'Sorry, no posts matched your criteria.\').\'</p></div>\';
            } // end if have_posts
      
      
       }
      
      
       ?>
      
      
      
       <script type="text/javascript">
      
       // Set starting values which to send from Javascript to WP query function...
       var ajaxurl = "<?php echo admin_url( \'admin-ajax.php\' ); ?>";
       var page = 2;                                                               // Infer page #2 to start, then increment at end
       var org_slug = "<?php echo $organisation->slug; ?>";                         // Slug of this "organisation" term
      
       jQuery(function($) {
      
            // When this selector is clicked
          $(\'body\').on(\'click\', \'.loadmore\', function() {
      
                 // Get ID of clicked link (corresponds to original $format value, eg. "executive"/"reporting")
                 var clicked_format = $(this).attr(\'id\');
      
                 // Temporarily change clicked-link text to provide feedback
                 $(\'a#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-cog fa-spin\');      // Icon
                 $(\'a#\'+clicked_format+\' .moretext\').text(\'Loading...\');               // Text
      
                 // Pick up data-page attribute from the clicked link (defaults to 2 at load)
                 var clicked_page = $(\'a#\'+clicked_format).find(\'span\').data().page;
                 // console.log(clicked_page);
      
      
                 // 1. Send this package of variables to WP query function
              var data = {
                  \'action\': \'load_posts_by_ajax\',
                  \'page\': clicked_page,
                      \'org_slug\': org_slug,
                      \'clicked_format\': clicked_format,
                  \'security\': \'<?php echo wp_create_nonce("load_more_posts"); ?>\'
              };
      
                 // 2. Send to query function and get results
              $.post(ajaxurl, data, function(response) {
      
                      // Append the returned output to this selector
                  $(response).appendTo(\'div#\'+clicked_format).hide().fadeIn(2000); // was: $(\'div#\'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
      
                      // Change link text back to original
                      $(\'a#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-plus-circle\'); // Icon
                      $(\'a#\'+clicked_format+\' .moretext\').text(\'More\');                // Text
      
                      // Increment "data-page" attribute of clicked link for next click
                  // page++;
                      $(\'a#\'+clicked_format).find(\'span\').data().page++
              });
      
      
      
      
      
          });
      
      
      
       });
       </script>
      
      函数中的函数。php:

        // Called from org_deck2_many.php
      
        add_action(\'wp_ajax_load_posts_by_ajax\', \'load_posts_by_ajax_callback\');
        add_action(\'wp_ajax_nopriv_load_posts_by_ajax\', \'load_posts_by_ajax_callback\');
      
        function load_posts_by_ajax_callback() {
            check_ajax_referer(\'load_more_posts\', \'security\');
      
            // 1. Query values are passed from referring page, to Javascript and to this query...
            $paged = $_POST[\'page\'];                               // Passed from page: Which page we are on
            $org_slug = $_POST[\'org_slug\'];                        // Passed from page: Organisation taxonomy term slug
            $clicked_format = $_POST[\'clicked_format\'];            // ID of the clicked "More" link (corresponds to original $format value, eg. "executive"/"reporting")
      
            // 2. Formulate the secondary tax_query for "format" with some conditionality
            /* *********************************** */
            /*           Posts by Format?          */
            /* *********************************** */
            if ($clicked_format!="reporting") {
                 $tax_q_format_array = array(
                      \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                      \'field\'    => \'slug\',
                      \'terms\'    => $clicked_format,
                      \'include_children\' => false
                 );
                 // $offset = NULL;
            /* *********************************** */
            /*         Posts without Format?       */
            /* *********************************** */
            } elseif ($clicked_format=="reporting") {
                 $tax_q_format_array = array(
                      \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                      \'operator\' => \'NOT EXISTS\', // or \'EXISTS\'
                 );
                 // $offset = \'12\';      // More articles shown in "Reporting"
            }
      
            // 3. Set query arguments
            $args = array(
                 // posts
                \'post_type\' => array( \'article\', \'viewpoint\' ),
                \'post_status\' => \'publish\',
                // \'offset\' => $offset,
                // pages
                \'posts_per_page\' => \'8\',
                \'paged\' => $paged,
                // taxonomy
                \'tax_query\' => array(
                  // #1 Organisation: the current one
                  array(
                   \'taxonomy\' => \'company\', // from above, whatever this taxonomy is, eg. \'source\'
                   \'field\'    => \'slug\',
                   \'terms\'    => $org_slug,
                   \'include_children\' => false
                  ),
                  // #2 Format: as above
                  $tax_q_format_array
                ),
            );
      
            // 4. Query for posts
            $posts_org = new WP_Query( $args );
      
            // 5. Send results to Javascript
            if ( $posts_org->have_posts() ) :
                ?>
                <?php while ( $posts_org->have_posts() ) : $posts_org->the_post(); ?>
                    <?php get_template_part(\'partials/loops/col\', \'vertical\'); ?>
                <?php endwhile; ?>
                <?php
            endif;
      
            wp_die();
        }
      
      编辑:如果所有帖子都被拉出来,不允许更多的轮询如果所有帖子/页面都被返回,我们应该如何停止允许更多的链接点击?

      在PHP中,此代码更新根据每页帖子数除以总帖子数,计算此查询的帖子总页数。

      它使用data-page 属性,以指示预期要拉取的下一分页页面。

      每次拉取一页结果时,该计数器都会递增。

      如果计数器超过了查询的帖子总页数,这意味着我们已经用完了此查询的帖子/页面,没有了,因此我们应该停止。

      “停止”是什么意思?这意味着使用jQuery选择器来查找和隐藏整个链接,否则可以单击该链接再次调用帖子。

               <?php
               $organisation = get_query_var(\'organisation\');
               $org_id_prefixed = get_query_var(\'org_id_prefixed\');
               ?>
      
      
               <?php
      
      
               /* ************************************************************************************************************** */
               /*                                                                                                                */
               /*          LIST POSTS BY FORMAT TERM, WITH DYNAMIC AJAX MORE-POST LOADING                                        */
               /*                                                                                                                */
               /*          Outline:                                                                                             */
               /*          This will output posts in blocks for each "Format" taxonomy term.                                     */
               /*          But we also want to use this loop to output posts *without* a "Format" taxonomy term.                 */
               /*          >> Method via Sajid @ Artisans Web, https://artisansweb.net/load-wordpress-post-ajax/                 */
               /*                                                                                                                */
               /*          Dynamic:                                                                                              */
               /*          1. Javascript: When "More" link is clicked                                                            */
               /*          2. Send current "organisation", clicked "format" and "page" as variables to function                  */
               /*          3. PHP: Do WP query for next page of posts, return to javascript                                      */
               /*          4. Javascript: Append results to the clicked container                                                */
               /*                                                                                                                */
               /*          Dynamic method:                                                                                       */
               /*          $format used as ID for i) .row .my-posts container and ii) .loadmore link, so that we know:           */
               /*          a) Which "Load more" link was clicked                                                                 */
               /*          b) Which box to return new output to                                                                  */
               /*          c) Employs data-page attribute in link - picks up this and increments page only for this              */
               /*          >> Help via Antti Koskinen @ StackOverflow, https://wordpress.stackexchange.com/a/328760/39300        */
               /*                                                                                                                */
               /* ************************************************************************************************************** */
      
      
               // Specify which "Format" terms we want to display post blocks for
               // ("reporting" here is a wildcard, used to accommodate posts without a "Format" term set)
               $formats = array("interview","executive","analyst","oped","reporting","ma","earnings","financialanalysis","ipo","marketindicators","industrymoves");
      
               // For each of them,
               foreach ($formats as $format) {
      
                          // 1. Get actual term of the slug above
                          $format_term = get_term_by(\'slug\', $format, "format");
      
                          // 2. Formulate the secondary tax_query for "format" with some conditionality
                          /* *********************************** */
                          /*           Posts by Format?          */
                          /* *********************************** */
                          if ($format!="reporting") {
                                   $posts_per_page = 8;
                                   $tax_q_format_array = array(
                                              \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                                              \'field\'    => \'slug\',
                                              \'terms\'    => $format_term->slug,
                                              \'include_children\' => false
                                   );
                                   // Oh, and set a title for output below
                                   $section_title = $format_term->name;
                          /* *********************************** */
                          /*         Posts without Format?       */
                          /* *********************************** */
                          } elseif ($format=="reporting") {
                                   $posts_per_page = 8;
                                   $tax_q_format_array = array(
                                              \'taxonomy\' => \'format\', // from above, whatever this taxonomy is, eg. \'source\'
                                              \'operator\' => \'NOT EXISTS\', // or \'EXISTS\'
                                   );
                                   // Oh, and set a title for output below
                                   $section_title = \'Reporting\';
                          }
      
                          // 3. Set query arguments
                          $paged = ( get_query_var( \'paged\' ) ) ? get_query_var( \'paged\' ) : 1;
                          $args = array(
                              // pagination
                              // \'nopaging\' => false,
                              \'posts_per_page\' => $posts_per_page,
                              // \'offset\' => \'4\',
                              \'paged\' => $paged,
                              // posts
                              \'post_type\' => array( \'article\', \'viewpoint\' ),
                              // order
                              \'orderby\' => \'date\',
                              \'order\'   => \'DESC\',
                              // taxonomy
                              \'tax_query\' => array(
                                  // #1 Organisation: the current one
                                  array(
                                      \'taxonomy\' => \'company\', // from above, whatever this taxonomy is, eg. \'source\'
                                      \'field\'    => \'slug\',
                                      \'terms\'    => $organisation->slug,
                                      \'include_children\' => false
                                  ),
                                  // #2 Format: as above
                                  $tax_q_format_array
                              ),
                          );
      
                          // 4. Query for posts
                          $posts_org = new WP_Query($args);
      
      
                          // 5. Output
                          if ( $posts_org->have_posts() ) { ?>
      
                                  <?php
                                  $total_posts = $posts_org->found_posts;
                                  $total_pages = $total_posts / $posts_per_page;
                                  ?>
      
                                   <h5 class="mt-0 pt-4 pb-3 text-secondary"><?php echo $section_title; ?> <span class="badge badge-secondary badge-pill"><?php echo $total_posts; ?></span></h5>
                                   <div class="row pb-0 my-posts" id="<?php echo $format; ?>" data-totalpages="<?php echo $total_pages; ?>">
                                   <?php
                                   while( $posts_org->have_posts() ) {
                                              $posts_org->the_post();
                                              get_template_part(\'partials/loops/col\', \'vertical\');
                                   }
                                   ?>
                                   </div>
                                   <?php
                                   // wp_reset_postdata(); // reset the query
      
                                   // "More" posts link
                                   if ($posts_org->found_posts > $posts_per_page) {
                                              echo \'<p class="text-secondary pb-0" style="opacity: 0.6"><a href="javascript:;" class="loadmore" id="\'.$format.\'"><i class="fas fa-plus-circle"></i> <span class="moretext" data-page="2">More</span></a></p>\';
                                   }
      
                          } else {
                                   // echo \'<div class="col"><p>\'.__(\'Sorry, no posts matched your criteria.\').\'</p></div>\';
                          } // end if have_posts
      
      
               }
      
      
               ?>
      
      
      
               <script type="text/javascript">
      
               // Set starting values which to send from Javascript to WP query function...
               var ajaxurl = "<?php echo admin_url( \'admin-ajax.php\' ); ?>";
               var page = 2;                                                               // Infer page #2 to start, then increment at end
               var org_slug = "<?php echo $organisation->slug; ?>";                         // Slug of this "organisation" term
      
               jQuery(function($) {
      
                          // When this selector is clicked
                  $(\'body\').on(\'click\', \'.loadmore\', function() {
      
                                   // Get ID of clicked link (corresponds to original $format value, eg. "executive"/"reporting")
                                   var clicked_format = $(this).attr(\'id\');
      
                                  // Get total pagination pages for this section
                                  var total_pages_for_section = $(\'div .row #\'+clicked_format).data().totalpages;
                                  // alert(total_pages_for_section);
      
                                   // Temporarily change clicked-link text to provide feedback
                                   $(\'a#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-cog fa-spin\');      // Icon
                                   $(\'a#\'+clicked_format+\' .moretext\').text(\'Loading...\');               // Text
      
                                   // Pick up data-page attribute from the clicked link (defaults to 2 at load)
                                   var clicked_page = $(\'a#\'+clicked_format).find(\'span\').data().page;
                                   // console.log(clicked_page);
      
      
                                   // 1. Send this package of variables to WP query function
                      var data = {
                          \'action\': \'load_posts_by_ajax\',
                          \'page\': clicked_page,   // page of posts to get is the number set in data-page attribute
                          \'org_slug\': org_slug,
                          \'clicked_format\': clicked_format,
                          \'security\': \'<?php echo wp_create_nonce("load_more_posts"); ?>\'
                      };
      
                       // 2. Send to query function and get results
                      $.post(ajaxurl, data, function(response) {
      
                          // Append the returned output to this selector
                          $(response).appendTo(\'div#\'+clicked_format).hide().fadeIn(2000); // was: $(\'div#\'+clicked_format).append(response).fadeIn(4000); Reverse method, cf. https://stackoverflow.com/a/6534160/1375163
      
                          // If we have exhausted all post pages, hide the whole "More" link <p>
                          if (clicked_page >= total_pages_for_section) {
                                  $(\'p a#\'+clicked_format).hide();
                          // Otherwise, restore it and increment counter
                          } else {
                              // Change link text back to original
                              $(\'a#\'+clicked_format+\' i\').attr(\'class\', \'fas fa-plus-circle\'); // Icon
                              $(\'a#\'+clicked_format+\' .moretext\').text(\'More\');                // Text
                              // Increment "data-page" attribute of clicked link for next click
                              $(\'a#\'+clicked_format).find(\'span\').data().page++; // was page++;
                          }
      
                      });
      
      
      
      
      
                  });
      
      
      
               });
               </script>