doushi2902 2019-04-04 19:03
浏览 115
已采纳

AJAX在while循环中干扰if语句?

I am trying to load my sidebars in my while loop by using if statements that call them after a certain number of posts. It's important to note that I am using AJAX code (provided below) to load in posts on scroll and I believe it may be causing the issue.

Though they are sidebars, they are not physically a sidebar but rather content loaded between posts.

I've tried for a week to locate the problem but I cannot seem to get the sidebars to load with AJAX as a if statement in the while loop.

Important to note: The sidebar will load after the number of posts if it's not loaded through AJAX. So if it's in the initial load, the sidebars load. But when you continue to scroll to say the third or fourth bar it will not load and the AJAX will only load the (parts/content).

I need to either be able to resolve the if statement so it works within the while loop that loads through AJAX or I'm open to an alternate solution as long as it doesn't remove the AJAX.

A lot of work has been put into making this loop work and help is greatly appreciated!

front-page.php

 <?php
  $current_page = max( 1, get_query_var( 'paged' ) );
  $the_query = new WP_Query( array(
    'cat'            => '-21',
    'post_type'      => 'post',
    'posts_per_page' => 5,
    'paged'          => $current_page,
    'tax_query'      => array(
        array(
            'taxonomy' => 'topics',
            'operator' => 'NOT EXISTS',
            'field' => 'term_id',
            'terms' => $term_id
        )
    )
  ) );

  wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
    'ajaxurl'      => admin_url( 'admin-ajax.php', 'relative' ),
    'posts'        => json_encode( $the_query->query_vars ),
    'current_page' => $current_page,
    'max_page'     => $the_query->max_num_pages
  ) );
?>

<div id="main" class="container-fluid">
    <?php if ($the_query->have_posts()) : ?>
      <?php $count = 0; ?>
      <?php while ($the_query->have_posts()) : $the_query->the_post(); get_template_part( 'parts/content', get_post_format() ); ?> <!-- This parts/content loads -->
      <?php $count++; ?>
 <!-- the dynamic_sidebar does not load -->
        <?php if ($count == 2 && is_active_sidebar('sidebar1') ) : ?>
          <div class="side-container first-side">

            <?php dynamic_sidebar('sidebar1'); ?>

          </div>

        <?php endif; ?>

        <?php if ($count == 10 && is_active_sidebar('sidebar2') ) : ?>
          <div class="side-container first-side">

            <?php dynamic_sidebar('sidebar2'); ?>

          </div>

        <?php endif; ?>

        <?php if ($count == 20 && is_active_sidebar('sidebar3') ) : ?>
          <div class="side-container third-side">

            <?php dynamic_sidebar('sidebar3'); ?>

          </div>
        <?php endif; ?>
      <?php endwhile; ?>
    <?php endif; ?>

  <?php wp_reset_postdata(); ?>

  <?php get_footer(); ?>
</div><!-- END CONTAINER -->

parts/content -- this loads as expected including code if it's helpful

<div class="row post"> <!-- Post is mentioned in the below JS to load -->
    <div class="col-sm-5">
     <h2>Text</h2>
    </div>

    <div class="col-sm-7">
      <h3>text</h3>
    </div>
</div><!-- END ROW-->

sidebar code - works when initially loaded but doesn't when AJAX calls on this code such as the last two sidebars in front-page.php

<?php
     $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?>
    <?php while( $flexible_posts->have_posts() ) : $flexible_posts->the_post(); global $post; ?>
    <div class="sidebar-area">
        //sidebar code here
    } 
endwhile;
?>

myloadmore.js - AJAX Call

jQuery(function($){
    var canBeLoaded = true,
    bottomOffset = 2000; 

    $(window).scroll(function(){
        if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
            return;
        }
        var data = {
            'action': 'loadmore',
            'query': misha_loadmore_params.posts,
            'page' : misha_loadmore_params.current_page
        };
        if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
            $.ajax({
                url : misha_loadmore_params.ajaxurl,
                data: data,
                type: 'POST',
                beforeSend: function( xhr ){
                    // AJAX call is in process, we shouldn't run it again until complete
                    canBeLoaded = false;
                },
                success:function(data){
                    if( data ) {
                        $('#main').find('div.post:last-of-type').after( data ); // where to insert posts
                        canBeLoaded = true; // the ajax is completed, now we can run it again
                        misha_loadmore_params.current_page++;
                        bottomOffset = ( $( '#main > div.post:last' ).offset() || {} ).top
                    }
                }
            });
        }
    });
});

functions.php - Added for further context

function misha_my_load_more_scripts() {
    wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js',
        array( 'jquery' ), '', true );
    wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );

function misha_loadmore_ajax_handler() {
    $args = json_decode( wp_unslash( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // load the next page

    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) :
        while ( $the_query->have_posts() ) : $the_query->the_post();
            get_template_part( 'parts/content', get_post_format() );
        endwhile;
    endif;

    wp_die();
}
add_action( 'wp_ajax_loadmore', 'misha_loadmore_ajax_handler' );        // Authenticated users
add_action( 'wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler' ); // Non-authenticated users
  • 写回答

1条回答 默认 最新

  • duangengruan2144 2019-04-20 08:46
    关注

    The trick here was to add the if statements inside of the AJAX handlers as well. Perhaps someone with AJAX experience can add to this one day to explain why it works, but all I know is that it does. All the code from my question is the same below is the difference from the functions.php ajax handler function.

    function misha_loadmore_ajax_handler() {
        $args = json_decode( wp_unslash( $_POST['query'] ), true );
        $args['paged'] = $_POST['page'] + 1; // load the next page
    
        $the_query = new WP_Query( $args );
    
        if ( $the_query->have_posts() ) :
            while ( $the_query->have_posts() ) : $the_query->the_post();
                get_template_part( 'parts/content', get_post_format() );
    
        <?php if ($count == 2 && is_active_sidebar('sidebar1') ) : ?>
          <div class="side-container first-side">
            <?php dynamic_sidebar('sidebar1'); ?>
          </div>
        <?php endif; ?>
    
        <?php if ($count == 10 && is_active_sidebar('sidebar2') ) : ?>
          <div class="side-container first-side">
            <?php dynamic_sidebar('sidebar2'); ?>
          </div>
        <?php endif; ?>
    
        <?php if ($count == 20 && is_active_sidebar('sidebar3') ) : ?>
          <div class="side-container third-side">
            <?php dynamic_sidebar('sidebar3'); ?>
          </div>
        <?php endif;
            endwhile;
        endif;
        wp_die();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog