I am trying to edit my main query using pre_get_posts to only display a particular custom post type and set posts per page to 5.
This is working, however since I have added the pre_get_posts filter my ACF get_field() functions no longer work and are returning as NULL. Any help with this issue would be appreciated.
Query
if (have_posts()) : while (have_posts()) : the_post();
$name = get_field('character_name');?>
<div class="col-md-4">
<h2><?php echo $name ?></h2>
</div>
<?php endwhile;endif; ?>
Pre Get Posts
function edit_query($query) {
if ( !is_admin() && $query->is_main_query() ) {
$query->set( 'post_type', 'cpt_operator' );
$query->set( 'posts_per_page', 5);
return $query;
}
}
add_action( 'pre_get_posts', 'edit_query');
The reason why is that you are setting all queries to only look in the post type ‘cpt_operator’. If you are trying to change the posts per page for this post type then you should not be setting the post type, you should be checking the query to see if WP is doing a query on that post type.
function edit_query($query) {
if ( !is_admin() && $query->is_main_query() &&
isset($query->query_vars['post_type']) &&
$query->query_vars['post_type'] == 'cpt_operator') {
$query->set( 'posts_per_page', 5);
return $query;
}
}
add_action( 'pre_get_posts', 'edit_query');