Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress: How to display only posts that are in a certain category?

I'm pretty new to WordPress but have spent some 50 odd hours studying up on it, trying things out and such and have the feeling I got a pretty good handle on it now..

However the one thing I simply cannot get working is to have a page spit out a list of posts of a certain category.

Here is my example: http://dev.jannisgundermann.com/zoeikin/graphic-design/typographic-posters

I have a post that if I go to it directly works correctly, but does not show up on this page.

The post direct link.

The category id is '3' while the category name is 'typographic-posters'.

I have a custom page template for the typographic-posters page that looks like this:

<?php
/*
Template Name: Typographic Posters
*/
?>

<?php get_header(); ?>
<?php get_sidebar(); ?>

<?php if (in_category('3')): ?>
<div class="post">

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>


  <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
   <div class="post-description">
    <h2><?php the_title(); ?></h2>
    <?php the_content(); ?>
   </div>
   <?=get_image('flutter-image');?>
  </div>


    <?php endwhile; else: ?>
     <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>

</div>
<?php endif; ?>

<?php get_footer(); ?>

Using this code however the page only shows gets the header, sidebar and nothing else..

If someone could help me out that would really help me get a handle on this filtering of wordpress categories.

Thanks for reading,

Jannis

like image 613
Jannis Avatar asked Oct 29 '25 07:10

Jannis


2 Answers

in_category will only work outside of the loop on a single page. I suggest using the query_posts function to solve this problem. You may use query_posts('cat=3') or query_posts('category_name=typographic-posters') to get the posts you are looking for.

Once obtained, just use the normal WordPress loop to access these posts.

like image 114
Karthik Viswanathan Avatar answered Oct 31 '25 00:10

Karthik Viswanathan


The easiest way is to create a file called category-3.php and use the standard code from normal index.php or category.php file. Wordpress will take care of fetching posts only from category with id=3 and it's child categories.

like image 20
Eimantas Avatar answered Oct 30 '25 23:10

Eimantas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!