WordPress.org

Forums

How Can I Use WP_Query to Display Posts from Only ONE Category? (20 posts)

  1. andymacdonalduk
    Member
    Posted 4 years ago #

    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?

  2. esmi
    Forum Moderator
    Posted 4 years ago #

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

  3. andymacdonalduk
    Member
    Posted 4 years ago #

    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?

  4. esmi
    Forum Moderator
    Posted 4 years ago #

    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.

  5. andymacdonalduk
    Member
    Posted 4 years ago #

    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!!!

  6. esmi
    Forum Moderator
    Posted 4 years ago #

    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

  7. andymacdonalduk
    Member
    Posted 4 years ago #

    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. :)

  8. esmi
    Forum Moderator
    Posted 4 years ago #

    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...

  9. andymacdonalduk
    Member
    Posted 4 years ago #

    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 ;-)

  10. andymacdonalduk
    Member
    Posted 4 years ago #

    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?

  11. esmi
    Forum Moderator
    Posted 4 years ago #

    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 ]
  12. andymacdonalduk
    Member
    Posted 4 years ago #

    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>
  13. esmi
    Forum Moderator
    Posted 4 years ago #

    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.

  14. andymacdonalduk
    Member
    Posted 4 years ago #

    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

  15. esmi
    Forum Moderator
    Posted 4 years ago #

    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>
  16. andymacdonalduk
    Member
    Posted 4 years ago #

    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;?>

  17. esmi
    Forum Moderator
    Posted 4 years ago #

    Spotted 1 error - I missed an opening <?php before if( $c == 4) :?>

    Amended code: http://wordpress.pastebin.com/PRtCYBw1

  18. andymacdonalduk
    Member
    Posted 4 years ago #

    Hey there Esmi,

    That did the trick perfectly, thank you very much! Are you able to give me a rough Idea of what exactly was done there please?

    You mentioned Id have to re-do my CSS which isn't a problem, but are you able to point me in the right direction on where roughly I need to be looking please?

    I guess what Im asking, is what has actually changed in the above code, which would mess up the css layout of the featured gallery, so I know where I should start looking so I can fix the changes?

    Thanks again. :-)

  19. andymacdonalduk
    Member
    Posted 4 years ago #

    Esmi, please ignore my last post.

    I have worked out the CSS layout and now have it working perfectly. Thanks again for your amazing help!! I really appreciate it.

  20. andymacdonalduk
    Member
    Posted 4 years ago #

    Esmi, I have a question, if you don't mind?

    You know you showed me how to have four of the latest posts from my 'Gallery' category show up in a four-column section of my home page?

    Is there a way to do exactly the same thing, but output categories instead? I have individual categories inside my gallery, but I want to create a gallery page which is specifically designed to be the 'springboard' to push people to those individual gallery categories.

    So for example. When somebody clicks on a gallery page, I want a page to be displayed which shows a list of categories inside the 'gallery' category. Maybe the icon for each category could be the latest picture added in the latest post inside that specific category.

    Does that make sense, and is anything like that possible?

Topic Closed

This topic has been closed to new replies.

About this Topic