WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Calling WP_Query within a foreach loop (5 posts)

  1. gregponchak
    Member
    Posted 4 years ago #

    Hi guys,
    I have been struggling to figure this out for a few hours now and cannot get anywhere.

    Basically, what I want this code to do is to list all of the categories and posts within them with content separated by categories.

    Here is my code:

    $categories=get_categories('orderby=name');
      		foreach ($categories as $cat) {
    			$the_query = new WP_Query('category_name='.$cat->cat_name);
    			while ($the_query->have_posts()) : $the_query->the_post();
    				echo "<div class=\"post\">";
    				echo "<b>";
    				echo "<a href=\"";
    				the_permalink();
    				echo "\">";
    				the_title();
    				echo "</a>";
    				echo "&mdash;";
    				the_time('M j, Y');
    				echo "</b>";
    				echo "<div class=\"content\">";
    				the_content('&mdash;');
    				echo "</div>";
    				echo "</div>";
    			endwhile;
      		}

    The script is working (somewhat). It lists the categories, but only displays the first post in each category. I want all of them to be displayed. Also, my blog posts per page is set to 50.

    I haven't really used WP_Query before (this is probably apparent to those who have), so any help would be greatly appreciated.

    Thanks,
    Greg

  2. esmi
    Forum Moderator
    Posted 4 years ago #

    Not tested but what about:

    $categories=get_categories('orderby=name');
    foreach ($categories as $cat) {
    	$the_query = new WP_Query('posts_per_page=-1&category_name='.$cat->cat_name);
    	while ($the_query->have_posts()) : $the_query->the_post();
    		echo '<div class="post">';
    		echo '<strong><a href="' . the_permalink() .">' . the_title() . '</a>&mdash;' . the_time('M j, Y') . echo '</strong>';
    		echo '<div class="content">';
    		the_content('&mdash;');
    		echo '</div></div>;
    	endwhile;
    }
    wp_reset_query();
  3. Bocq
    Member
    Posted 4 years ago #

    Bonjour Greg, bonjour Esmi,

    did you find your solution?
    Would you help me to do the same thing with years instead of categories?
    I also want the articles to be in alphabetical order within each year.

    The result I need is:
    Category Name (as title of my page)
    Year 2010
    Author A
    Author B
    Author C
    Year 2009
    Author A
    Author B
    Author C

    Now it looks like this: http://valentine-meunier.de/wordpress/?cat=13

    I've been searching for a long time but I can't find the way to get back the year as a variable.
    I hope it will interest someone .
    Merci!

  4. MichaelH
    Member
    Posted 4 years ago #

    Bocq - please start another thread with that question.

  5. Bocq
    Member
    Posted 4 years ago #

    I'll do it right now, Michael.

Topic Closed

This topic has been closed to new replies.

About this Topic