I'm using the following code to output the custom posts that belongs to a tag:

add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
    if(is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
        $post_type = get_query_var('post_type');
        if($post_type) :
            $post_type = $post_type;
            $post_type = array('btp_work'); // replace cpt to your custom post type
    return $query;

It works well if the tag has less than 10 posts (my pagination settings are on 10 posts), for example if I go to mysite.com/tag/cars it shows the custom posts that the tag cars has.

The problem is when there are a lot of custom posts associated to a tag. The tag page adds pagination but there is no custom posts showing:

enter image description here

Any idea what could be the problem here?

It seems WP knows how many posts are since it shows four pages and creates the pagination but it's strange no custom posts on any of it...


Your code has a couple of flaws which I'm not going to go into detail now. Here is a short list

  • pre_get_posts is an action

  • On any type of archive page you need to make sure you only target the main query and the front end when using pre_get_posts

  • Your syntax is very hard to debug and not supported by most code editors. Although if (): else : endif; is valid php, it is not recommended due the trouble debugging it. Use proper curlies like if () { } else { }

  • Most of your code does not make much sense. Please see my code and compare it with yours

You can rewrite your code as follows

add_action( 'pre_get_posts', function ( $q )
    if (     !is_admin() // Make sure you only target the front end 
          && $q->is_main_query() // Only target the main query
          && $q->is_tag() // Only target the tag pages
    ) {
        $q->set( 'post_type', array( 'post', 'btp_work' ) ); // Change as necessary
| improve this answer | |
  • Thanks Pieter, works perfectly! Nice explanation also :) – wpuser Jun 29 '15 at 22:18

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.