1
votes

I have a static page with 10 containers located at different places in the index.php file, i want to show the 10 latest posts. I want to echo the data for a post (title,text,thumbnail,author,time) like this:

       <div class="text">
         <?php
            echo '$textfrompost3';
         ?>   
    </div>

 <div class="title">
     <?php
        echo '$titlefrompost3';
     ?>   
    </div>

      ...
      ...

My PHP file:

<?php 
   // the query
   $the_query = new WP_Query( array(
     'category_name' => 'Allgemein',
      'posts_per_page' => 10,
       "orderby"        => "date",
         "order"          => "DESC"
   )); 

?>

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



  // insert values into variables


  <?php endwhile; ?>
  <?php wp_reset_postdata(); ?>


<?php endif; ?>

Thanks in advance, i appreciate any help you can provide.

1
not working because its printing the posts just under each other in a loop i want the data for the 10 latest posts in variables or something else - Karl B.
Try this then possibly ? wordpress.stackexchange.com/questions/217299/… - Thats what google returned when searching for "get result of WP_QUERY into variables" - John Cogan

1 Answers

1
votes

I'd simply replace your call to WP_Query with get_posts() which will provide an array of post objects.

$latest_posts = get_posts( array(
    'category_name'  => 'Allgemein',
    'posts_per_page' => 10,
) );

I've dropped order and orderby in the example above. While you may well have a different global setting for the number of posts to display, it's unlikely you're modifying the default ordering.

Documentation: https://codex.wordpress.org/Template_Tags/get_posts

So let's say I want to output the title of the third post, I could do the following:

// let's be sure we have a third post.
if ( isset( $latest_posts[2] ) ) { 
    echo $latest_posts[2]->post_title; // remember arrays have a zero-based index.
}