Skip to content

Instantly share code, notes, and snippets.

@RiodeJaneiroo
Last active March 27, 2019 13:34
Show Gist options
  • Save RiodeJaneiroo/a3cb80328496900ca39b9d99eefdad53 to your computer and use it in GitHub Desktop.
Save RiodeJaneiroo/a3cb80328496900ca39b9d99eefdad53 to your computer and use it in GitHub Desktop.
[Wordpress ajax load post on click button] Ajax load posts click button #wordpress #ajax
/**
* Javascript for Load More
*
*/
function be_load_more_js() {
$query = array(
'posts_per_page' => 6,
'post_type' => 'reviews'
);
$args = array(
'url' => admin_url( 'admin-ajax.php' ),
'query' => $query,
);
wp_enqueue_script( 'be-load-more', get_stylesheet_directory_uri() . '/js/load-more.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'be-load-more', 'beloadmore', $args );
}
add_action( 'wp_enqueue_scripts', 'be_load_more_js' );
/**
* AJAX Load More
*
*/
function be_ajax_load_more() {
$args = isset( $_POST['query'] ) ? array_map( 'esc_attr', $_POST['query'] ) : array();
$args['post_type'] = isset( $args['post_type'] ) ? esc_attr( $args['post_type'] ) : 'post';
$args['paged'] = esc_attr( $_POST['page'] );
$args['post_status'] = 'publish';
ob_start();
$loop = new WP_Query( $args );
if( $loop->have_posts() ): while( $loop->have_posts() ): $loop->the_post();
?>
<div class="item-reviews">
<div class="review-photo">
<img src="<?php echo kama_thumb_src('w=120&h=90', get_the_post_thumbnail_url())?>" alt="<?php the_title();?>">
</div>
<div class="review-info">
<div class="review-top">
<div class="review-name"><?php the_title();?></div>
<a href="#" class="link"><?php the_field('soc_link')?></a>
</div>
<p class="review-date"><?php the_date();?></p>
<div class="dfl">
<?php the_content(); ?>
</div>
</div>
</div>
<?php
endwhile; else:
echo 'empty';
endif; wp_reset_postdata();
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
add_action( 'wp_ajax_be_ajax_load_more', 'be_ajax_load_more' );
add_action( 'wp_ajax_nopriv_be_ajax_load_more', 'be_ajax_load_more' );
jQuery(function($){
var page = 2;
var loading = false;
$('body').on('click', '#more_reviews', function(){
if( ! loading ) {
loading = true;
var data = {
action: 'be_ajax_load_more',
page: page,
query: beloadmore.query,
};
$.post(beloadmore.url, data, function(res) {
if(res.data == "empty") {
$('#more_reviews').hide();
return true;
}
if( res.success) {
$('.reviews-list').append( res.data );
page = page + 1;
loading = false;
} else {
console.log(res);
}
}).fail(function(xhr, textStatus, e) {
console.log(xhr.responseText);
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment