• Resolved nncrns

    (@nncrns)


    This is my first time coding a WP theme, so please bear with me if this is a stupid question. πŸ™‚ I’ve already looked for similar threads and have tried different solutions, but I still can’t get my code to work. If anyone could have a look at what I might be doing wrong I would appreciate it.

    I am trying to display posts by categories. There is a category menu to the left and when selecting a category, its posts should load right beside it. However, what it does right now is display the posts of *all* categories.

    <div class="one-column category-menu">
       <?php wp_nav_menu( array( 'theme_location' => 'category-menu' ) ); ?>
    </div>
    
    <div class="four-columns">
    
       <?php get_query_var( $category );
       echo get_query_var('cat');
       query_posts('cat=$category'); ?>
    
       <?php if (have_posts()) : ?>
          <?php while (have_posts()) : the_post(); ?>
    
             <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
                <div class="entry">
                   <?php the_content(); ?>
                </div>
             </div>
    
         <?php endwhile; ?>
       <?php endif; ?>
    
    </div>
Viewing 2 replies - 1 through 2 (of 2 total)
  • I don’t understand exactly what you’re trying to do, but I’ve changed your code a little. It should work now.

    <div class="one-column category-menu">
    	<?php
    
    	wp_nav_menu(array(
    		'theme_location' => 'category-menu',
    	));
    
    	?>
    </div>
    
    <div class="four-columns">
    	<?php
    
    	$category = get_query_var('cat');
    
    	query_posts('cat='.$category);
    
    	?>
    	<?php if (have_posts()): ?>
    		<?php while (have_posts()): ?>
    			<?php the_post(); ?>
    			<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
    				<div class="entry">
    					<?php the_content(); ?>
    				</div>
    			</div>
    		<?php endwhile; ?>
    	<?php endif; ?>
    </div>

    Take a look at:

    1. Template Hierarchy
    2. The Loop
    3. WP Query
    Thread Starter nncrns

    (@nncrns)

    Awesome! Thanks so much for your help! Your corrections didn’t quite fix the problem, but it made me realise my mistake and now it works πŸ™‚
    I didn’t know that the proper way to adress the variable was this:

    query_posts('cat='.$category);

    I thought by using get_query_var I could get the category IDs, store them in $category and query the posts with that ID to show up. Now I found out that the categories are automatically stored inside $cat and all I had to do was replace the code block including get_query_var with this:

    <?php query_posts('cat='.$cat);?>

    πŸ™‚

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Displaying posts by category doesn't work’ is closed to new replies.