My pagination is throwing a 404 error when the posts from General -> Reading are smaller than my custom number of posts on my custom taxonomy cities
(custom post type city
). From what I saw on SO this issue can be fixed usually by using a filter of pre_get_posts, but don't know how to apply it on my case.
I want to mention that in the taxonomy-cities.php
I am getting posts of a category of a custom taxonomy of a custom post type.
taxonomy-cities.php
$cat_ID = get_query_var('cities');
$custom_id = get_term_by('slug', $cat_ID, 'cities');
add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_orderby($orderby_statement) {
global $aPostsIDs;
$orderby_statement = 'FIELD(ID, '.implode(',',$_SESSION['saved_city_ids']).')';
return $orderby_statement;
}
$offset = ($paged - 1) * $num_city_guides_post;
$args['post_type'] = 'city';
$args['posts_per_page'] = $num_city_guides_post; // 5
$args['orderby'] = $orderby; // rand
$args['order'] = $order; // DESC
$args['paged'] = $paged; // 1
$args['tax_query'] = array(
array(
'taxonomy' => 'cities',
'field' => 'id',
'terms' => array($custom_id->term_id) // 3742
)
);
}
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
// some code here
endwhile;
else: echo 'No Posts';
endif;
wp_reset_postdata();
For archive-city.php
I am using this filter in the functions.php and it works fine, but it doesn't get applied to the taxonomy-cities.php
so I get 404:
function portfolio_posts_per_page_city( $query ) {
if (array_key_exists('post_type', $query->query_vars)) {
if ( $query->query_vars['post_type'] == 'city' )
$num_city_guides_post = get_option('num_city_post');
if( empty( $num_city_guides_post ) )
$num_city_guides_post = 9;
$query->query_vars['posts_per_page'] = $num_city_guides_post;
return $query;
}
}
if ( !is_admin() ) add_filter( 'pre_get_posts', 'portfolio_posts_per_page_city' );
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…