Support » Fixing WordPress » WP_Query with one category in args shows other categories

  • Hi all.

    I need to list titles of the default WP posts of “blog” category in my blog page, which has “Blog” title and uses page-blog.php as template with the following code in it:

    <article>
    <?php
    	$args = array(
    	 'post_type' => 'post',
    		'category_name' => 'blog'
    	);
    
    	$query = new WP_Query( $args );
     if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
    ?>
    	<h1><?php the_title(); ?></h1>
    
    <?php
    	endwhile;
    	wp_reset_postdata();
    	else :
    ?>
    	<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
    	<?php endif; ?>
    
    	</article>

    No matter what I try it keeps showing all WP posts, regardless to which category they assigned to… even though the same code works perfectly with my custom post types.

    Please help!
    Thanks.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You shouldn’t need to do a custom query (or page template) to view posts in a certain category. Just go to Posts > Categories and click “View” under the category.

    Thread Starter willkanoff

    (@willkanoff)

    Thanks for the reply.

    I did it this way in order to display a featured image at the top of the blog page…

    The bad news is that I found out that when I try to view “blog” category the way you describe, it still shows all the default posts. Moreover, categories assigned to custom post types show nothing, but working on the front end. This is weird. It has probably something to do with the archive template.
    I’ll get to it…

    In Settings > Reading. The page you have set as Page for posts, is the slug for it blog? You might just be looking at the page for all posts. Try adding something to “Category base”, see if that changes what the view link does.

    Thread Starter willkanoff

    (@willkanoff)

    I didn’t set Page for posts in Settings > Reading. I use dynamic front-page.php instead of index.php.

    I got “blog” category showing correct posts. It had a child news category, I completely forgot about… I am an idiot!

    Now I only need to figure out why custom post type categories do not show anything…

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘WP_Query with one category in args shows other categories’ is closed to new replies.