Guys I am a little stuck here. Unable to load posts from a custom post type through AJAX. Normally I have had been using this script http://goo.gl/lwfM5 It seems so that $wp_query is not getting the post-type identification. What should I do? Summarised question will be "How to implement a LOAD MORE button through AJAX for the posts of a Custom Post Type?"

The PHP File


  * Initialization. Add our script if needed on this page.
 function pbd_alp_init() {
    global $wp_query;

    // Add code to index pages.
    if( !is_singular() ) {  
        // Queue JS and CSS
            plugin_dir_url( __FILE__ ) . 'js/load-posts.js',

            plugin_dir_url( __FILE__ ) . 'css/style.css',

        // What page are we on? And what is the pages limit?
        $max = $wp_query->max_num_pages;
        $paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;

        // Add some parameters for the JS.
                'startPage' => $paged,
                'maxPages' => $max,
                'nextLink' => next_posts($max, false)
 add_action('template_redirect', 'pbd_alp_init');


The js file

jQuery(document).ready(function($) {

    // The number of the next page to load (/page/x/).
    var pageNum = parseInt(pbd_alp.startPage) + 1;

    // The maximum number of pages the current query can return.
    var max = parseInt(pbd_alp.maxPages);

    // The link of the next page of posts.
    var nextLink = pbd_alp.nextLink;

     * Replace the traditional navigation with our own,
     * but only if there is at least one page of new posts to load.
    if(pageNum <= max) {
        // Insert the "More Posts" link.
            .append('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>')
            .append('<p id="pbd-alp-load-posts"><a href="#">Load More Posts</a></p>');

        // Remove the traditional navigation.

     * Load new posts when the link is clicked.
    $('#pbd-alp-load-posts a').click(function() {

        // Are there more posts to load?
        if(pageNum <= max) {

            // Show that we're working.
            $(this).text('Loading posts...');

            $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post',
                function() {
                    // Update page number and nextLink.
                    nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);

                    // Add a new placeholder, for when user clicks again.
                        .before('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>')

                    // Update the button message.
                    if(pageNum <= max) {
                        $('#pbd-alp-load-posts a').text('Load More Posts');
                    } else {
                        $('#pbd-alp-load-posts a').text('No more posts to load.');
        } else {
            $('#pbd-alp-load-posts a').append('.');

        return false;

I think $WP_QUERY is not getting to identify the post type. Looking forward.

Update here is my custom post type named as aa_portfolio this file below is the template file where I want the posts to be loaded by ajax

<?php // get_header(); ?>

    <!-- #content BEGIN  -->
    <div id="aa_port_wrap" class="aa_510">

                <ul class="aa_filter clear">
                    <li class="aa_active"><a href="javascript:void(0)" class="all">All</a></li>

                        // Get the taxonomy
                        $terms = get_terms('filter', $args);

                        // set a count to the amount of categories in our taxonomy
                        $count = count($terms); 

                        // set a count value to 0

                        // test if the count has any categories
                        if ($count > 0) {

                            // break each of the categories into individual elements
                            foreach ($terms as $term) {

                                // increase the count by 1

                                // rewrite the output for each category
                                $term_list .= '<li><a href="javascript:void(0)" class="'. $term->slug .'">' . $term->name . '</a></li>';

                                // if count is equal to i then output blank
                                if ($count != $i)
                                    $term_list .= '';
                                    $term_list .= '';

                            // print out each of the categories in our new format
                            echo $term_list;

                <ul class="aa_filterable_grid clear">

                        // Set the page to be pagination
                        $paged = get_query_var('paged') ? get_query_var('paged') : 1;

                        // Query Out Database
                        $aa_portQuery = new WP_Query(array( 'post_type' => 'aa_portfolio', 'posts_per_page' =>'9', 'paged' => $paged ) ); 

                        // Begin The Loop
                        if ($aa_portQuery->have_posts()) : while ($aa_portQuery->have_posts()) : $aa_portQuery->the_post(); 

                        // Get The Taxonomy 'Filter' Categories
                        $terms = get_the_terms( get_the_ID(), 'filter' ); 

                    $large_image =  wp_get_attachment_image_src( get_post_thumbnail_id(get_the_ID()), 'fullsize', false, '' ); 
                    $large_image = $large_image[0]; 

                                //Apply a data-id for unique indentity, 
                                //and loop through the taxonomy and assign the terms to the aa_portfolio item to a data-type,
                                // which will be referenced when writing our Quicksand Script
                            <li data-id="id-<?php echo $count; ?>" data-type="<?php foreach ($terms as $term) { echo strtolower(preg_replace('/\s+/', '-', $term->name)). ' '; } ?>">

                                        // Check if wordpress supports featured images, and if so output the thumbnail
                                        if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) : 

                                        <?php // Output the featured image ?>
                                        <a rel="prettyPhoto[gallery]" href="<?php echo $large_image ?>"><?php the_post_thumbnail('aa_portfolio_img'); ?></a>                                    

                                    <?php endif; ?> 

                                    <?php // Output the title of each aa_portfolio item ?>
                                    <p><a href="<?php the_permalink(); ?>"><?php echo get_the_title(); ?></a></p>


                    <?php $count++; // Increase the count by 1 ?>       
                    <?php endwhile; endif; // END the Wordpress Loop ?>
                    <?php wp_reset_query(); // Reset the Query Loop?>

                <!-- /#aa_load_more -->



                    $big = 999999999;
                    echo paginate_links(array(
                        'base' => str_replace($big, '%#%', get_pagenum_link($big)),
                        'format' => '?paged=%#%',
                        'current' => max(1, get_query_var('paged')),
                        'total' => $aa_portQuery->max_num_pages,
                            'prev_text' => __('Previous'),
    'next_text' => __('Next'),

    </div><!-- #content END -->

<?php // get_footer(); ?>

This is how I created the Custom Post Type


// function: post_type BEGIN
function aa_post_type()
    // Create The Labels (Output) For The Post Type
    $labels = 
        // The plural form of the name of your post type.
        'name' => __( 'Portfolio'), 

        // The singular form of the name of your post type.
        'singular_name' => __('Portfolio'),

        // The rewrite of the post type
        'rewrite' => 
                // prepends our post type with this slug
                'slug' => __( 'portfolio' ) 

        // The menu item for adding a new post.
        'add_new' => _x('Add Item', 'portfolio'), 

        // The header shown when editing a post.
        'edit_item' => __('Edit Portfolio Item'),

        // Shown in the favourites menu in the admin header.
        'new_item' => __('New Portfolio Item'), 

        // Shown alongside the permalink on the edit post screen.
        'view_item' => __('View Portfolio'),

        // Button text for the search box on the edit posts screen.
        'search_items' => __('Search Portfolio'), 

        // Text to display when no posts are found through search in the admin.
        'not_found' =>  __('No Portfolio Items Found'),

        // Text to display when no posts are in the trash.
        'not_found_in_trash' => __('No Portfolio Items Found In Trash'),

        // Used as a label for a parent post on the edit posts screen. Only useful for hierarchical post types.
        'parent_item_colon' => '' 

    // Set Up The Arguements
    $args = 
        // Pass The Array Of Labels
        'labels' => $labels, 

        // Display The Post Type To Admin
        'public' => true, 

        // Allow Post Type To Be Queried 
        'publicly_queryable' => true, 

        // Build a UI for the Post Type
        'show_ui' => true, 

        // Use String for Query Post Type
        'query_var' => true, 

        // Rewrite the slug
        'rewrite' => true, 

        // Set type to construct arguements
        'capability_type' => 'post', 

        // Disable Hierachical - No Parent
        'hierarchical' => false, 

        // Set Menu Position for where it displays in the navigation bar
        'menu_position' => null, 

        // Allow the portfolio to support a Title, Editor, Thumbnail
        'supports' => 

    // Register The Post Type
    register_post_type(__( 'aa_portfolio' ),$args);

} // function: post_type END

// function: portfolio_messages BEGIN
function aa_portfolio_messages($messages)
    $messages[__( 'aa_portfolio' )] = 
            // Unused. Messages start at index 1
            0 => '',

            // Change the message once updated
            1 => sprintf(__('Portfolio Updated. <a href="%s">View Portfolio</a>'), esc_url(get_permalink($post_ID))),

            // Change the message if custom field has been updated
            2 => __('Custom Field Updated.'),

            // Change the message if custom field has been deleted
            3 => __('Custom Field Deleted.'),

            // Change the message once portfolio been updated
            4 => __('Portfolio Updated.'),

            // Change the message during revisions
            5 => isset($_GET['revision']) ? sprintf( __('Portfolio Restored To Revision From %s'), wp_post_revision_title((int)$_GET['revision'],false)) : false,

            // Change the message once published
            6 => sprintf(__('Portfolio Published. <a href="%s">View Portfolio</a>'), esc_url(get_permalink($post_ID))),

            // Change the message when saved
            7 => __('Portfolio Saved.'),

            // Change the message when submitted item
            8 => sprintf(__('Portfolio Submitted. <a target="_blank" href="%s">Preview Portfolio</a>'), esc_url( add_query_arg('preview','true',get_permalink($post_ID)))),

            // Change the message when a scheduled preview has been made
            9 => sprintf(__('Portfolio Scheduled For: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview Portfolio</a>'),date_i18n( __( 'M j, Y @ G:i' ),strtotime($post->post_date)), esc_url(get_permalink($post_ID))),

            // Change the message when draft has been made
            10 => sprintf(__('Portfolio Draft Updated. <a target="_blank" href="%s">Preview Portfolio</a>'), esc_url( add_query_arg('preview','true',get_permalink($post_ID)))),
    return $messages;   

} // function: portfolio_messages END

// function: portfolio_filter BEGIN
function aa_portfolio_filter()
    // Register the Taxonomy
    register_taxonomy(__( "filter" ), 

    // Assign the taxonomy to be part of the portfolio post type
    array(__( "aa_portfolio" )), 

    // Apply the settings for the taxonomy
        "hierarchical" => true, 
        "label" => __( "Filter" ), 
        "singular_label" => __( "Filter" ), 
        "rewrite" => array(
                'slug' => 'filter', 
                'hierarchical' => true
} // function: portfolio_filter END

add_action('init', 'aa_post_type');
add_action( 'init', 'aa_portfolio_filter', 0 );
add_filter('post_updated_messages', 'aa_portfolio_messages');

  • What is the purpose of $aa_portQuery? It's created then never used. How come you didn't use the WP AJAX API? – Tom J Nowell Aug 12 '14 at 16:53
  • I edited the post and now it has my cpt loop and the above PHP file is reverted back to what I read in the tutorial linked in first para. Thanks. Looking forward. – Ahmad Awais Aug 12 '14 at 16:58
  • As an aside, wp_reset_query is for when you've used query_posts, you don't use it for WP_Query loops. Also your first file refers to a function next_posts but there is no such function in WordPress core. My understanding of the code you've posted is that you should see a fatal PHP error on every post archive you try to look at. So your issue is that you're getting posts, you actually want aa_portfolios? And this is on the homepage? index.php is just the fallback template in the template hierarchy, it isn't the homepage/frontpage. – Tom J Nowell Aug 12 '14 at 17:15
  • I have corrected the function. It was next_post. Whereas I have a portfolio it is showing up and the Load More button is not working to load more posts below it. I have a custom page templates as home. Which is portfolio page. – Ahmad Awais Aug 12 '14 at 17:28
  • We will need to see that custom page template, we will need to see everything that is related. But before all of that, can you confirm, your current implementation shows normal posts when you click load? The last piece of code you posted, what is the file name? Is it a complete file? You said it was aa_portfolio but didn't specify what file it was, is that index.php? home.php? single.php? single-aa_portfolio? It isn't a custom page template because it doesn't have the comment at the top – Tom J Nowell Aug 12 '14 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.