-1

I try to create a page that shows my posts (a page different than the "posts page" defined in wp-admin).

When I copy my index.php into this new page and add

<?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>

above the

    <?php if ( have_posts() ) : ?>
...
...

then everything works fine - my posts are shown. If I try to put

 <?php   get_posts(); ?>

instead of

<?php query_posts('post_type=post&posts_per_page=5&paged='.get_query_var('paged')); ?>

the posts are not showing.

Since everyone suggests that get_posts() is preferable in general over query_posts(), I wonder how can I have the posts showing, using get_posts().

  • 2
    query_posts() does alter the main query, which is the reason that works for you - you still shouldn't use query_posts() though. Take a look at the get_posts() and WP_Query and pre_get_posts documentation to know your options. – Nicolai Oct 27 '15 at 14:35
  • I certainly looked at get_posts() but couldn't understand why it doesn't get the posts in my case. – IXN Oct 27 '15 at 15:15
  • sorry, no time to teach you, otherwise I would have written an answer, but if you look at the documentation it should be clear – Nicolai Oct 27 '15 at 15:20
1

Every page has a "main query" which is run before the template is loaded. The results of the main query are how WordPress determines what template to load. The standard Loop operates on the data contained in the main query, this is why it seems to just magically "work" without you having to explicitly query something yourself.

query_posts overwrites the contents of that main query. This is why you shouldn't use query_posts- you're changing the query results after the template is loaded, which can have unexpected consequences. pre_get_posts is the preferred way to modify the main query, it runs before the main query happens, so that everything that follows is operating on the correct set of data.

get_posts and WP_Query are for running additional queries, separate from the main query. You have to assign the results to a variable, and run some sort of loop on those results. Your use of get_posts is doing nothing, because you've done nothing with the results of that query.

0

The thing is that, contrary to popular belief, pre_get_posts does not work for single Page requests.1 Not even for is_front_page().

As for get posts(), in order to work I needed to use a syntax like:

<?php global $post;
$myposts = get_posts();
foreach( $myposts as $post ) :  setup_postdata($post); ?>
    ...
<?php endforeach; 
wp_reset_postdata(); ?>

instead of

<?php get_posts(); while ( have_posts() ) : the_post(); ?>
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.