Как заставить AJAX загружать больше для работы с пользовательскими постами, связанными с Wordpress? - PullRequest
1 голос
/ 18 мая 2019

Я использую учебник из этого поста для реализации функциональности Ajax Load More. https://rudrastyh.com/wordpress/load-more-posts-ajax.html

Я успешно реализовал это на своей странице архива для всех постов блога. Однако у меня естьнесколько разделов «Связанные сообщения», в которых используются пользовательские запросы WP, которые я не могу заставить работать. Я попробовал решение в этом комментарии: https://rudrastyh.com/wordpress/load-more-posts-ajax.html#comment-1055

Он загружает новые сообщения, но они не придерживаютсяаргументы пользовательского запроса (в частности, отображаются сообщения только в той же категории).

Пользовательский запрос работает (он отображает 4 связанных сообщения из той же категории). Когда я загружаю больше, он несоблюдайте нумерацию страниц (загружает 6 сообщений вместо 4) и не учитывает запрос (загружает сообщения не в той же категории).

<div class="related-blog-posts gray-bg pt-5 pb-5 blog">
  <div class="related-title pb-3">
        <h1 class="mb-2">Related Stories</h1>
        <img src="/dcustom/wp-content/uploads/2019/04/Path-137@2x.png" />
      </div><!-- scroll-down-->    

      <div class="container">
      <div class="row">

        <?php

        $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;

              $query_args = array(

                'category__in'   => wp_get_post_categories( $post->ID ),
                'paged' => $paged,
                'post_type' => 'post', 
                 'posts_per_page' => 4,
                 'post__not_in'   => array( $post->ID ),
                     'orderby' => 'date',
        'order' => 'DESC'
              );

        $third_query = new WP_Query( $query_args ); ?>


  <?php

//Loop through posts and display...
    if($third_query->have_posts()) : ?>
     <?php while ($third_query->have_posts() ) : $third_query->the_post(); ?>

                <?php get_template_part('template-parts/content-related-blog-posts'); ?>

      <?php endwhile; ?><!-- end the loop-->
<?php endif; ?>
    <?php wp_reset_postdata(); ?>

 <?php // don't display the button if there are not enough posts
if (  $third_query->max_num_pages > 1 )
  echo '<a class="custom_loadmore btn btn-primary">More posts</a>'; // you can use <a> as well
?>

<?php endif; ?><!-- end loop if--->
              </div><!-- row -->

            </div><!-- container -->
</div><!-- related-case-studies-->


  <script>
    var test = '<?php echo serialize( $third_query->query_vars ) ?>',
    current_page_myajax = 1,
    max_page_myajax = <?php echo $third_query->max_num_pages ?>
</script>
<script src="<?php bloginfo('template_url')?>/js/myloadmore.js"></script>
jQuery(function($){ // use jQuery code inside this to avoid "$ is not defined" error
    $('.misha_loadmore').click(function(){

        var button = $(this),
            data = {
            'action': 'loadmore',
            'query': misha_loadmore_params.posts, // that's how we get params from wp_localize_script() function
            'page' : misha_loadmore_params.current_page
        };

        $.ajax({ // you can also use $.post here
            url : misha_loadmore_params.ajaxurl, // AJAX handler
            data : data,
            type : 'POST',
            beforeSend : function ( xhr ) {
                button.text('Loading...'); // change the button text, you can also add a preloader image
            },
            success : function( data ){
                if( data ) { 
                    button.text( 'More posts' ).prev().after(data); // insert new posts
                    misha_loadmore_params.current_page++;

                    if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page ) 
                        button.remove(); // if last page, remove the button

                    // you can also fire the "post-load" event here if you use a plugin that requires it
                    // $( document.body ).trigger( 'post-load' );
                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });



$('.custom_loadmore').click(function(){
        //custom query on front-page.php
        var button = $(this),
            data = {
            'action': 'loadmore',
            'query': test,
            'page' : current_page_myajax
        };

        $.ajax({
            url : '/dcustom/wp-admin/admin-ajax.php', // AJAX handler
            data : data,
            type : 'POST',
            beforeSend : function ( xhr ) {
                button.text('Loading...'); // change the button text, you can also add a preloader image
            },
            success : function( data ){
                if( data ) { 
                    button.text( 'More posts' ).prev().after(data); // insert new posts
                    current_page_myajax++;

                    if ( current_page_myajax == max_page_myajax )
                        button.remove(); // if last page, remove the button
                } else {
                    //button.remove(); // if no data, remove the button as well
                }
            }
        });
    }); 

    }); 
function misha_my_load_more_scripts() {

        global $wp_query; 

    // In most cases it is already included on the page and this line can be removed
    wp_enqueue_script('jquery');

    // register our main script but do not enqueue it yet
    wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );

    // now the most interesting part
    // we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
    // you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
    wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
        'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
        'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
        'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
        'max_page' => $wp_query->max_num_pages,
    ) );

    wp_enqueue_script( 'my_loadmore' );
}

add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );


/* AJAX LOOP FOR THE ARCHIVE PAGE */
function misha_loadmore_ajax_handler(){

    // prepare our arguments for the query
    $args = json_decode( stripslashes( $_POST['query'] ), true );
    $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
    $args['post_status'] = 'publish';

    // it is always better to use WP_Query but not here
    query_posts( $args );

    if( have_posts() ) :

        // run the loop
        while( have_posts() ): the_post();

            // look into your theme code how the posts are inserted, but you can use your own HTML of course
            // do you remember? - my example is adapted for Twenty Seventeen theme

            get_template_part( 'template-parts/content-index', get_post_format() );

            // for the test purposes comment the line above and uncomment the below one
            // the_title();

        endwhile;

    endif;
    die; // here we exit the script and even no wp_reset_query() required!
}



add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...