Ajax load in function slow down page
-
Hi
Hi there
I have a question about the new function I put in the site, it’s ajax load more post for the custom post type, but I think it’s slow down my page load, the scroll thing take a while to finish, and click load more button need to wait for whole page load to actually function, is any way to avoid that, or make page load faster?1. I thought maybe this code limited in only work for this template, how can I wrap this function using if( template_name){
}function.php
//load more 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'); $paged = $_POST['page']; $args = array( 'post_type' => 'books', 'post_status' => 'publish', 'posts_per_page' => 5, 'order' => 'DESC', 'paged' => $paged, ); $my_posts = new WP_Query( $args ); if ( $my_posts->have_posts() ) : ?> <?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?> <?php get_template_part( 'template-parts/content', 'page' ); ?> <?php endwhile ?> <?php endif; wp_die(); }
My script code
// {ID} is any unique name, example: b1, q9, qq, misha etc, it should be unique let ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; let page = 2; jQuery(function($) { $('body').on('click', '.loadmore', function() { var data = { 'action': 'load_posts_by_ajax', 'page': page, 'security': '<?php echo wp_create_nonce("load_more_posts"); ?>', 'max_page': '<?php echo $my_query->max_num_pages; ?>' }; $.post(ajaxurl, data, function(response) { console.log() $('.content').append(response); page++; }) if(page == data['max_page']){ $('.loadmore').fadeOut(); } }); }); </script>
Thank you guys so much
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Ajax load in function slow down page’ is closed to new replies.