I've created a custom post type called 'award':
function award_post_type() {
$labels = array(
'name' => 'Awards',
'singular_name' => 'Award'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'supports' => array( 'title', 'editor', 'excerpt' )
);
register_post_type( 'award', $args );
}
add_action( 'init', 'award_post_type' );
Now I am in the award post type's page archive, and I'm trying to display a list of awards ordered by the awards' deadlines (which are stored in a custom field). Next posts should be loaded via AJAX at the click of a 'Load More' button.
First thing I did was alter the main query using pre_get_posts
:
function order_by_deadline( $query ) {
if ( ! is_admin() && is_post_type_archive( 'award' ) ) {
if( $query->is_main_query() ) {
$query->set( 'orderby', 'deadline' );
$query->set( 'meta_key', 'deadline' );
}
}
}
add_action( 'pre_get_posts', 'order_by_deadline' );
This works okay. But when I try to load the next posts using AJAX, no results are shown. Here's the action I pass to the AJAX call, which includes the custom WP_Query I've created to call the new posts:
function load_next_awards() {
// The number of the page is received from an attribute of the Load More button. I'm 100% sure this has nothing to do with the issues I'm having, so just ignore it.
$page = $_POST[ 'page' ];
$args = array(
'paged' => $page,
'post_type' => 'award',
'post_status' => 'publish'
'post__not_in' => get_option( 'sticky_posts' ),
'orderby' => 'meta_value_num',
'meta_key' => 'deadline'
);
$next_posts = new WP_Query( $args );
if( $next_posts->have_posts() ) :
while( $next_posts->have_posts() ) : the_post();
get_template_part( 'views/post/content', get_post_format() );
endwhile;
endif;
wp_reset_postdata();
die();
}
I'm at a loss of ideas. The custom WP_Query looks correct to me, but it returns no results when I click on 'Load More'. If I change the post_type
parameter to post
or page
instead, it does correctly show my posts and pages.
echo $post->post_title;
?$next_posts
after the query is run, specifically$next_posts->request
, you'll see exactly what is being queried.var_dump($next_posts)
it’s completely empty? Not the posts array, the actual SQL query inrequest
is empty?"SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'cal' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC LIMIT 8, 8"