Last active
August 29, 2015 13:57
-
-
Save FutureMedia/38091a4d82c772d18bf8 to your computer and use it in GitHub Desktop.
Load custom post type posts in a page via AJAX
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
jQuery(document).ready(function($){ | |
$('#load-more button').click(function(e){ | |
e.preventDefault(); // revent normal form submission | |
var postoffset = $('.item').length; // count props on page | |
$.post( WPaAjax.ajaxurl, | |
{ | |
action : 'props_more', | |
postoffset : postoffset, | |
}, | |
function( response ) { | |
l.stop(); | |
$('#props-container').append( response ); | |
if ( postoffset * 2 >= $( '#postsnumber' ).val() ) { // hide more button | |
$('#load-more button').hide(); | |
} | |
} | |
); | |
}); | |
}); |
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 | |
// add to function.php | |
function props_ajax_paging() { | |
wp_enqueue_script( | |
'ajax_paging', | |
get_template_directory_uri() . '/assets/js/ajax-paging.js?ver=1.0', | |
array( 'jquery' ), | |
null, | |
false | |
); | |
wp_localize_script( | |
'ajax_paging', | |
'WPaAjax', | |
array( | |
'ajaxurl' => admin_url( 'admin-ajax.php' ) | |
) | |
); | |
} | |
add_action( 'wp_enqueue_scripts', 'props_ajax_paging', 100 ); | |
function props_more(){ | |
global $ajaxquery; | |
$offset = $_POST['postoffset']; | |
$args = array( | |
'offset' => $offset, | |
'post_type' => 'properties', | |
'post_status' => 'publish', | |
'posts_per_page' => 15, | |
//'nonce' => wp_create_nonce('ajax_custom_load_posts'), | |
); | |
$ajaxquery = new WP_Query( $args ); | |
$row = 0; | |
while ($ajaxquery->have_posts()) : | |
$ajaxquery->the_post(); | |
if ( $row == 0 ) echo '<div class="row">' ; // counter | |
get_template_part( 'loop', 'properties' ); // or $post->post_type for general use | |
$row++; | |
if ( $row == 3 ) : | |
echo '</div>'; | |
$row = 0; | |
endif; | |
endwhile; | |
exit; | |
} | |
add_action('wp_ajax_props_more', 'props_more'); | |
add_action('wp_ajax_nopriv_props_more', 'props_more'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment