WordPress.org

Support

Support » How-To and Troubleshooting » How Can I Use WP_Query to Display Posts from Only ONE Category?

How Can I Use WP_Query to Display Posts from Only ONE Category?

  • Hey Guys,

    I have searched the internet for the last hour trying to look for a solution to my problem, but I either cannot find it, or am looking for the wrong thing.

    I am using…

    <?php $recent = new WP_Query(“showposts=3”); while($recent->have_posts()) : $recent->the_post();?>

    …to display some recent posts in my sidebar. It works really well. So I want to use it to display 3 posts from a specific category, on my blogs homepage.

    I have the working code on my home page, its displaying the correct number of posts, but I cannot work out how to make it only show posts from a specific category. In this case, I want only posts from the ‘Gallery’ category, to show up. That cat number is 10.

    What do I have to add to the code to make it only show posts from that category please?

Viewing 15 replies - 1 through 15 (of 19 total)
  • esmi

    @esmi

    Forum Moderator

    Try <?php $recent = new WP_Query("showposts=3&cat=10");

    Fantastic, that did the job perfectly.

    I tried a few variations which were similar to what you have put, but they were all guesses, so thanks for the tip.

    While we are on the subject, is there a way which can do pretty much the same thing, but exclude any posts from in X category?

    esmi

    @esmi

    Forum Moderator

    Just add a minus sign in front of the id for the category you want to exclude. So, for example, if you wanted to display 3 posts from cat 10 but wanted to exclude any posts from cat 15 (a child of cat 10), you could use:

    <?php $recent = new WP_Query("showposts=3&cat=10,-15");

    See http://codex.wordpress.org/Function_Reference/query_posts for more examples.

    Thank you! That worked perfectly.

    I have one last question, then I will stop bothering you!!

    I now have my ‘Gallery’ category featured on the home page, thats all working fine. I have setup the ‘latest posts’ in my sidebar not to display the gallery category.

    Now I need to have the wordpress loop also not display any posts from the gallery category – so there are no duplicates on the home page.

    I ‘think’ the bit of code I need to edit is <?php while (have_posts()) : the_post(); ?>

    I tried using your tip from above for on the WP_Query, but that didn’t work. This is what I changed it to: <?php while (have_posts(“cat=-10”)) : the_post(); ?>

    The category still seems to be displayed. What am I doing wrong please?

    And thanks so much for all your help. You really do amazing for a service which is free, so thank you for all the amazing work you do!!!

    esmi

    @esmi

    Forum Moderator

    Just before the start of the Loop (<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>), you need to set up a new query that excludes your Gallery category. Assuming the id of the Gallery category is 15, something like:

    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args= array(
    	'cat' => -15,
    	'paged' => $paged
    );
    query_posts($args);
    ?>

    should work.

    http://codex.wordpress.org/Function_Reference/query_posts

    That did the job perfectly, thank you!

    All these different querys and pieces of code can get quite complicated for a regular user like me, so your advice is much appreciated. I learn a lot around here. 🙂

    esmi

    @esmi

    Forum Moderator

    The only thing you have to be wary of is multiple Loops on the same page. Because you’ve used a new WP_Query() for each of your previous Loops, you should be fine. However, a couple of query_posts on the same page without any wp_reset_query() between them and you can get some very strange results…

    Ahh I see! I will keep that in mind.

    Just in case you are interested, here is the finished result of what I wanted to achieve with all of the above: http://purebeyonce.com/

    Obviously the latest posts displayed on the home page, as per normal, minus the gallery category. The featured Gallery Posts along the top. And in the sidebar, the most popular posts, along with a thumbnail beside each.

    Still an awful lot of work and customising of the theme left to do, so unfortunately for you, I doubt this will be the last time we speak over the next few weeks 😉

    I was just thinking, instead of having the featured gallery section at the top, is there a way to place it after X amount of posts on the home page?

    Im not sure whether that is possible?

    esmi

    @esmi

    Forum Moderator

    It should be. All it should need is a counter added to the main Loop which can then be checked to see if the second (featured gallery) Loop should be run. So the logic would go something like:

    <?php $counter = 0; // set up the counter
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args= array(
    	'cat' => -15,
    	'paged' => $paged
    );
    query_posts($args);
    if ( have_posts() ) : while ( have_posts() ) : the_post(); $counter ++; // increment the counter
    if( $counter == 4 ) {
    // we've displayed 4 posts so now start the featured gallery loop
    $recent = new WP_Query("showposts=3&cat=10"); // set up the featured query
    [ do the featured Loop ]
    } else {
    [ continue with the main Loop ]

    Hi there,

    Thanks for getting back to me. Sorry for being so dumb, but I don’t really understand the above code, and how to actually implement it into my own code. I just had a play around with it, and kept getting syntax errors.

    If I post the code im currently using on my index.php file below, would you be able to inset the code around what I have please? I try my best to understand everything, but the above has me a bit confused. I hope you don’t mind. 🙂

    <div class="wpn_expandable">
    
    <div id="related">
    
    <h1>Latest Gallery</h1>
    
    	<ul><?php $recent = new WP_Query("showposts=5&cat=10"); while($recent->have_posts()) : $recent->the_post();?>
    
    	    <li><a href="<?php the_permalink(); ?>"><?php $thumb = get_post_meta($post->ID, "wppt_preset4", true); if($thumb) echo ' <img style="border:3px solid #393939;" src="'.$thumb.'" alt="" />'; ?>
    <div id="yarp"><?php the_title(); ?></a></div>
    </a></li>
    	    <?php endwhile; ?>
    	</ul>
    
    </div>
    
    <ul class="wpn_news">
    
    <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args= array( 'cat' => -10, 'paged' => $paged ); query_posts($args); ?>
    			<?php while (have_posts()) : the_post(); ?>
    				<li <?php post_class() ?> id="post-<?php the_ID(); ?>">
    					<a class="wpn_title" href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    					<div class="wpn_info">
    						<?php echo get_avatar( get_the_author_email(), '40' ); ?>
    						by <?php the_author_posts_link() ?><br />
    						Posted <?php the_time('F jS, Y \a\t g:i a') ?> <div style="float:right;" class="share"><script type="text/javascript"> tweetmeme_url = '<?php the_permalink(); ?>';tweetmeme_source = 'swiftmed'; tweetmeme_style = 'compact';</script><script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script><iframe src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink(); ?>&layout=button_count&show_faces=false&width=70&action=like&colorscheme=light&height=25" scrolling="no" frameborder="0" style="border:none; background-color:DAE9EC; overflow:hidden; width:70px; height:25px; margin-bottom:-3px; margin-right:-3px; margin-left:-20px;" allowTransparency="true"></iframe></div>
    					</div>
    					<?php
    					$thumb = get_post_meta($post->ID, "wppt_preset1", true);
    					if($thumb)
    					echo '<img class="wpn_thumb" src="'.$thumb.'" alt="" />';
    					?>
    					<div class="wpn_post">
    						<?php the_excerpt(); ?>
    					</div>
    					<div class="wpn_bottom">
    						<a class="wpn_comments" href="<?php the_permalink() ?>#comments"><strong><?php comments_number(__('0'), __('1'), __('%')); ?></strong> Comments</a>
    						<a class="wpn_continue" href="<?php the_permalink() ?>">Continue Reading</a>
    					</div>
    				</li>
    			<?php endwhile; ?>
    
    			</ul>
    			<!-- Page Navigation -->
    			<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
    		</div>

    esmi

    @esmi

    Forum Moderator

    There’s a potential markup issue in that code. You’d be trying to insert a list (the featured gallery) inside a list (the main Loop). The only way to do that would be to turn the entire Gallery section into a list item – which would probably mean re-doing your CSS.

    Hey,

    I don’t mind re-doing my CSS, although Im not brilliant at it, with a bit of time, I always end up working my styling out. It’s just the markup that I have a problem with. :s

    esmi

    @esmi

    Forum Moderator

    Try:

    <div class="wpn_expandable">
    
    <ul class="wpn_news">
    
    <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $c = 0;
    $args= array( 'cat' => -10, 'paged' => $paged ); query_posts($args); ?>
    			<?php while (have_posts()) : the_post(); $c++;?>
    
    			if( $c == 4) :?>
    			<li><div id="related">
    			<h1>Latest Gallery</h1>
    
    				<ul><?php $recent = new WP_Query("showposts=5&cat=10"); while($recent->have_posts()) : $recent->the_post();?>
    
    					<li><a href="<?php the_permalink(); ?>"><?php $thumb = get_post_meta($post->ID, "wppt_preset4", true); if($thumb) echo ' <img style="border:3px solid #393939;" src="'.$thumb.'" alt="" />'; ?>
    			<div id="yarp"><?php the_title(); ?></a></div>
    			</a></li>
    					<?php endwhile; ?>
    				</ul>
    
    			</div></li>
    			<?php else : ?>
    
    				<li <?php post_class() ?> id="post-<?php the_ID(); ?>">
    					<a class="wpn_title" href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
    					<div class="wpn_info">
    						<?php echo get_avatar( get_the_author_email(), '40' ); ?>
    						by <?php the_author_posts_link() ?><br />
    						Posted <?php the_time('F jS, Y \a\t g:i a') ?> <div style="float:right;" class="share"><script type="text/javascript"> tweetmeme_url = '<?php the_permalink(); ?>';tweetmeme_source = 'swiftmed'; tweetmeme_style = 'compact';</script><script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script><iframe src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink(); ?>&layout=button_count&show_faces=false&width=70&action=like&colorscheme=light&height=25" scrolling="no" frameborder="0" style="border:none; background-color:DAE9EC; overflow:hidden; width:70px; height:25px; margin-bottom:-3px; margin-right:-3px; margin-left:-20px;" allowTransparency="true"></iframe></div>
    					</div>
    					<?php
    					$thumb = get_post_meta($post->ID, "wppt_preset1", true);
    					if($thumb)
    					echo '<img class="wpn_thumb" src="'.$thumb.'" alt="" />';
    					?>
    					<div class="wpn_post">
    						<?php the_excerpt(); ?>
    					</div>
    					<div class="wpn_bottom">
    						<a class="wpn_comments" href="<?php the_permalink() ?>#comments"><strong><?php comments_number(__('0'), __('1'), __('%')); ?></strong> Comments</a>
    						<a class="wpn_continue" href="<?php the_permalink() ?>">Continue Reading</a>
    					</div>
    				</li>
    				<?php endif;?>
    			<?php endwhile; ?>
    
    			</ul>
    			<!-- Page Navigation -->
    			<?php if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?>
    		</div>

    Thanks for the reply.

    I have some syntax errors when pasting in that code. The error it produces is “Parse error: syntax error, unexpected T_ELSE in /home/beyonce/public_html/wp-content/themes/Elements/index.php on line 28”

    The lines which have red marks beside them are:

    Line 29: <?php else : ?>

    Line 50: <?php endif;?>

Viewing 15 replies - 1 through 15 (of 19 total)
  • The topic ‘How Can I Use WP_Query to Display Posts from Only ONE Category?’ is closed to new replies.
Skip to toolbar