Last active
November 23, 2017 23:34
-
-
Save AustinGil/a2c797debda44b0acf8282a29ade72bc to your computer and use it in GitHub Desktop.
AJAX load more posts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function assets() { | |
// enqueue your script | |
wp_enqueue_script('handle', get_template_directory_uri() . '/path/to/main.js', ['jquery'], '$ver', true); | |
// localize script | |
wp_localize_script('handle', 'custom_ajaxify', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); | |
} | |
add_action('wp_enqueue_scripts', 'assets', 100); | |
/** | |
* AJAX load template part | |
*/ | |
function ajax_load_posts() { | |
global $post; | |
// Get the queryVars sent over from the AJAX request | |
$query_vars = $_POST['queryVars']; | |
$args = array( | |
'post_type' => $query_vars['post_type'], | |
'posts_per_page' => $query_vars['posts_per_page'], | |
'offset' => $query_vars['offset'], | |
'update_post_term_cache' => false, // Improves Query performance | |
'update_post_meta_cache' => false, // Improves Query performance | |
); | |
$posts = get_posts($args); | |
// The array of data we will return to the AJAX call | |
$payload = array( | |
'posts' => array(), | |
'query_vars' => $query_vars // Here for debugging purposes so we can console.log later | |
); | |
if ( $posts ) : | |
foreach ( $posts as $post ) : setup_postdata( $post ); | |
// Use object buffering to send each post as a separate string instead of all at once. | |
ob_start(); | |
get_template_part('templates/list-item', get_post_type()); | |
array_push($payload['posts'], ob_get_clean() ); | |
endforeach; | |
wp_reset_postdata(); | |
endif; | |
// We always send some data, even if there are no posts. | |
echo json_encode($payload); | |
die(); | |
} | |
add_action('wp_ajax_nopriv_ajax_load_posts', 'ajax_load_posts'); | |
add_action('wp_ajax_ajax_load_posts', 'ajax_load_posts'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** AJAX load posts **/ | |
function appendData(dataArray) { | |
for ( var i = 0; i < dataArray.length; i++ ) { | |
var markup = dataArray[i]; | |
// Convert HTML string into DOM object of new document | |
var postDocument = new DOMParser().parseFromString(markup, "text/html"); | |
// Get the post DOM object | |
var post = postDocument.body.firstChild; | |
var animationDelay = 0.3 * i; | |
post.style.animationDelay = animationDelay + 's'; | |
postsContainer.append(post); | |
} | |
} | |
function noMorePosts() { | |
// This function runs after we've loaded the final post. | |
loadPostsBtn.remove(); | |
} | |
var latestPostsSection = $('#home-latest-posts'), | |
postsContainer = $('#home-latest-posts .posts-list'), | |
loadPostsBtn = $('#ajax-load-more button'), | |
btnText = loadPostsBtn.text(), | |
queryVars = loadPostsBtn.data('query-vars'), | |
postsPerPage = queryVars.posts_per_page, | |
offset = queryVars.offset, | |
totalCount = loadPostsBtn.data('total'); | |
loadPostsBtn.click( function(event) { | |
// console.log(queryVars); | |
event.target.innerHTML = '<i class="icon-spin1 animate-spin"></i>'; | |
$.ajax({ | |
url: visceral_ajaxify.ajaxurl, | |
type: 'post', | |
data: { | |
action: 'ajax_load_posts', | |
queryVars: queryVars | |
}, | |
beforeSend: function(){ | |
latestPostsSection.attr("data-loading", "true"); | |
}, | |
complete: function(){ | |
latestPostsSection.attr("data-loading", "false"); | |
}, | |
success: function(jsonData) { | |
// console.log(jsonData); | |
event.target.innerHTML = btnText; | |
var data = JSON.parse(jsonData); | |
// console.log(data); | |
if ( offset + postsPerPage >= totalCount) { | |
appendData( data.posts ); | |
noMorePosts(); | |
} else { | |
appendData( data.posts ); | |
} | |
}, | |
error: function(MLHttpRequest, textStatus, errorThrown){ | |
alert(errorThrown); | |
} | |
}); | |
// Increment the offset | |
offset += postsPerPage; | |
queryVars.offset = offset; | |
}); | |
/** END AJAX load posts **/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$posts_per_page = 5; | |
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1; | |
$args = array( | |
'post_type' => 'post', | |
'posts_per_page' => $posts_per_page, | |
'paged' => $paged, | |
'update_post_term_cache' => false, // Improves Query performance | |
'update_post_meta_cache' => false, // Improves Query performance | |
); | |
$ajax_args = array( | |
'post_type' => 'post', | |
'posts_per_page' => $posts_per_page, | |
'offset' => $posts_per_page | |
); | |
$query = new WP_Query($args); ?> | |
<?php if ( $query->have_posts() ) : ?> | |
<section id="latest-posts"> | |
<div class="posts-list"> | |
<?php while ($query->have_posts()) : $query->the_post(); ?> | |
<?php get_template_part('templates/list-item', get_post_type()); ?> | |
<?php endwhile; ?> | |
</div> | |
<?php // Pagination | |
$total = $query->max_num_pages; | |
// only bother with pagination if we have more than 1 page | |
if ( $total > 1 ) : ?> | |
<p id="ajax-load-more" class="js-show text-center"><button data-query-vars=<?php echo json_encode($ajax_args); ?> data-total="<?php echo $query->found_posts; ?>"><?php _e('More', 'visceral'); ?></button></p> | |
<noscript> | |
<nav class="pagination text-center"> | |
<?php | |
// Set up pagination to use later on | |
$big = 999999999; // need an unlikely integer | |
$pagination = paginate_links( array( | |
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), | |
'format' => '?paged=%#%', | |
'current' => $paged, | |
'total' => $total, | |
'type' => 'plain', | |
'prev_next' => true, | |
'prev_text' => __('Next', 'theme_slug'), | |
'next_text' => __('Previous', 'theme_slug') | |
) ); | |
echo $pagination; ?> | |
</nav> | |
</noscript> | |
<?php endif; ?> | |
<?php else : ?> | |
<?php // No posts :( ?> | |
<?php endif; ?> | |
<?php wp_reset_postdata(); // Don't forget this ?> | |
</section> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment