WordPress

posty — ładowanie WordPress Ajax nie działa

  • 17 stycznia, 2023
  • 4 min read
posty — ładowanie WordPress Ajax nie działa


Witaj, skonfigurowałem niestandardowe ładowanie Ajax bez wtyczek, ale pokazuje tylko 3 posty na stronie głównej, a po kliknięciu przycisku, aby załadować więcej, nic się nie ładuje. Ponieważ jestem początkującym, jestem prawie pewien, że popełniłem kilka błędów w kodowaniu. Wydaje mi się, że mogłem popełnić błąd w pliku index.php

Oto kody, których użyłem:

Najpierw dodałem to do functions.php

function bsubash_load_more_scripts() {
    wp_enqueue_script('jquery');
    wp_register_script( 'loadmore_script', get_stylesheet_directory_uri() . '/js/ajax.js', array('jquery') );
    wp_localize_script( 'loadmore_script', 'loadmore_params', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ) );

    wp_enqueue_script( 'loadmore_script' );
}
 
add_action( 'wp_enqueue_scripts','bsubash_load_more_scripts' );

Następnie pod tym samym wierszem dodałem to

function bsubash_loadmore_ajax_handler(){
    $type = $_POST['type'];
    $category = isset($_POST['category']) ? $_POST['category']: '';
    $args['paged'] = $_POST['page'] + 1;
    $args['post_status'] = 'publish';
    $args['posts_per_page'] =  $_POST['limit'];
    if($type == 'archive'){
        $args['category_name'] = $category;
    }
    query_posts( $args );
    if( have_posts() ) :
        while(have_posts()): the_post();    
//write your single post card   
            the_title();
the_excerpt();
    endwhile;
    endif;
    die;
}
add_action('wp_ajax_loadmore','bsubash_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore','bsubash_loadmore_ajax_handler');

Następnie w moim index.php dodałem ten kod do kodu, którego używam do wyświetlania moich postów na stronie głównej

<div class="container"> <!-- container start -->
    <div class="row overflow-hidden"> <!-- row start -->
    <?php
      $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
      $latests = new WP_Query(array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'paged' => $paged
      ));
      
      while($latests->have_posts()): $latests->the_post();
            ?>
            <div class="col-xs-6 col-sm-6 col-md-6 col-lg-4 col-xl-3"> <!-- columns start -->
                <a href="<?php the_permalink(); ?>">
                    <div class="title-box mx-auto mb-0">
                        <h1 class="title-color">
                            <?php
                                $the_title = get_the_title();
                            if ( $the_title ) {
                                echo esc_html( the_title() );
                            } else {
                                echo 'No Title';
                            }
                            ?>
                        </h1>
                        <?php
                        if ( has_post_thumbnail() ) {
                            the_post_thumbnail('homepage-thumbnail', array('class' => 'featured-image'));
                        } else {
                            ?>
                                <img class="img-fluid" src="<?php echo esc_url_raw( get_template_directory_uri() . '/images/bg.jpg' ); ?>">
                                <?php
                        }
                        ?>
                    </div>
                </a>
            </div>
            <?php
        endwhile; // End of the loop.
        ?>
    </div>
</div> <!-- container ends -->

<script>
   var limit = 5,
       page = 1,
       type="latest",
       category = '',
       max_pages_latest = <?php echo $latests->max_num_pages ?>
</script>
<?php if ( $latests->max_num_pages > 1 ){
   echo '<div class="load_more text-center">
                    <a href="#" class="btn btn-circle btn-inverse btn-load-more">More Article</a> 
                </div>';
        }else{?>
<article>
   <h1>Sorry...</h1>
   <p><?php _e('Sorry, No Posts Available !'); ?></p>
</article>
<?php }
   wp_reset_query();
   ?>


i na koniec dodałem pliki js do /js/ajax.php

jQuery(function($) {
    $('.btn-load-more').click(function(e) {
        e.preventDefault();
        var button = $(this),
            data = {
                'action': 'loadmore',
                'limit': limit,
                'page': page,
                'type': type,
                'category': category
            };

        $.ajax({
            url: loadmore_params.ajaxurl,
            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) {
$(".latest_posts_wrapper").append(data);
                    page++;
                    button.text('More Articles');
                    if (page == max_pages_latest)
                        button.remove(); // if last page, remove the button
                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });

});


Źródło

Warto przeczytać!  rozwój wtyczek - Pojedyncze wywołanie zwrotne dotyczące sanityzacji dla wielu pól