category.php displays ALL posts instead of just those with the current category

I’m simply trying to display a list of categorised posts (with the custom post type of ‘project’) on the default category.php page. I can’t get it to work!

If I simply use the base theme category.php template I get a ‘No posts available’ message as it is looking for standard WP posts with a specified category (and there are none). However once I try and get the template to use my custom post type instead it simply prints a list of ALL the projects – no matter what category they are assigned to.

Read More

My current code is as follows:

<section>
<?php 
query_posts(array( 
'post_type' => 'project'
 ));  
 ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<article>
    <h2>Project: <?php the_title(); ?></h2>
    <?php the_content(); ?>    
</article>
    <?php endwhile; ?>
</section>

The template should ‘know’ what category it is supposed to be displaying by default. If I’m on www.mysite.co.uk/category/client-x then it should be showing only those projects that have the category ‘client x’. I’m sure this can’t be too hard!

Any help would be greatly appreciated.

Thanks

Dan

Related posts

Leave a Reply

1 comment

  1. Your problem is your use of query_posts(). Don’t use query_posts(), ever.

    Filter pre_get_posts instead. For example:

    function wpse74093_filter_pre_get_posts( $query ) {
        // First, make sure we target only the main query
        if ( is_main_query() ) {
            // Target the category index archive,
            // and only for the category "client-x"
            if ( is_category( 'client-x' ) ) {
                // Set the post-type to "project"
                $query->set( 'post-type', 'project' );
            }
        }
        return $query;
    }
    add_action( 'pre_get_posts', 'wpse74093_filter_pre_get_posts' );
    

    I’m assuming the appropriate category term is client-x, based on the category archive index URL in your question. If that’s not the right category, replace as appropriate.