0

I just want to show the last post from all categories on my page. For I could do this, I've made the following code:

<?php
    $args = array(
      'orderby' => 'name',
      'order' => 'ASC'
      );

    $categories = get_categories($args);

    foreach($categories as $category) {
        $categoryId = $category->cat_ID;

        query_posts('posts_per_page=1&cat=$categoryId');
        if ( have_posts() ) :
            while ( have_posts() ) : the_post(); ?>
                <h1><?php the_title(); ?></h1>
                <span><?php echo $categoryId; ?></span>
        <?php
            endwhile;
        endif;
    }
        wp_reset_query();
?>

But the posts displayed are all the same. What I've forgot?

Adam
  • 33
  • 8
  • Possible duplicate of [how do i get only 1 post from each category in wordpress](http://stackoverflow.com/questions/3264323/how-do-i-get-only-1-post-from-each-category-in-wordpress) – rnevius Oct 29 '15 at 17:39

2 Answers2

1

Your problem is here:

'posts_per_page=1&cat=$categoryId'

There's a significant difference between single and double quotes. Single quotes are for string literals. Variable interpolation requires double quotes.

Change it to either:

'posts_per_page=1&cat='.$categoryId

Or:

"posts_per_page=1&cat={$categoryId}"
maiorano84
  • 11,574
  • 3
  • 35
  • 48
  • Happens to the best of us, brotato. If this answered your question, make sure to accept it once you're able. – maiorano84 Oct 29 '15 at 17:39
-1

Please use argument like this:

    $args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'posts_per_page' =>'-1'
  );

posts_per_page = -1 used to fetch all posts.

Atif Tariq
  • 2,650
  • 27
  • 34