Support » Fixing WordPress » Querying custom post types with cat

  • Resolved blg002

    (@blg002)


    Am I missing something. The following returns nothing:

    <?php query_posts('post_type=my_custom_post_type&showposts=3&cat=185'); ?>

    Yes i have posts categorized that way, and there is the for loop, etc. If i remove the cat argument it displays the posts as normal. Is there something I have to do to get custom post types to make the cat argument in a query_posts work?

Viewing 3 replies - 1 through 3 (of 3 total)
  • C W (VYSO)

    (@cyril-washbrook)

    First thought: you shouldn’t be using query_posts. I can’t think of any situation where it is appropriate to use it. As stated succinctly in the introduction to the Codex page:

    Note: This function isn’t meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. Double Note: query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose. TL;DR don’t use query_posts() ever.

    Additionally, showposts is deprecated and has been for a long time, by which I mean seven years.

    Switch to WP_Query and see whether something like the following works:

    <?php
    $args = array( 'post_type' => 'my_custom_post_type', 'posts_per_page' => 3, 'cat' => '185' );
    $wp_query_current = new WP_Query( $args );
    while ( $wp_query_current->have_posts() ) : $wp_query_current->the_post(); ?>
    <!-- Do stuff -->
    <?php endwhile; wp_reset_postdata(); ?>

    If the problem persists, then come back to us with a more detailed description of what you’re doing, because “etc.” doesn’t really tell us anything much.

    Thread Starter blg002

    (@blg002)

    Ah good to know, I’ll have to go through and switch everything to that syntax. Bt ‘etc.’ I just meant it’s not one of those silly things like not have a post with that category, etc. :).

    FWIW: I did find a solution using the old query_posts syntax. I just had to put the ‘featured’ category in the context of the cutom taxonomy, e.g.:

    <?php query_posts('post_type=talks&showposts=3&uc_talks_cat=featured'); ?>

    Thread Starter blg002

    (@blg002)

    And with the ‘proper’ syntax it looks like:

    <?php $query = new WP_Query(array(
        'post_type'      => 'talks',
        'posts_per_page' => 3,
        'talks_cat'   => 'featured',
      ));
    
      while ( $query->have_posts() ) : $query->the_post();
    ?>
    
      <?php the_title(); ?><br>
    
    <?php endwhile; wp_reset_postdata(); ?>
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Querying custom post types with cat’ is closed to new replies.