Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress change the order of posts through the standard loop

Tags:

php

wordpress

is it possible to order posts while keeping the standard Wordpress loop intact (i.e. without having to create a whole new WP_Query?

By standard loop I mean:

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


            <?php /* The loop */ ?>
            <?php while ( have_posts() ) : the_post(); ?>

Can I specify the order within this code?

like image 554
Kev Avatar asked Oct 27 '13 12:10

Kev


People also ask

How do I change the order of posts in WordPress?

After activating it click into “Post Types Order” under settings and you can enable the types of posts you want the reorder interface to show up on. Then under that post type you will see a new menu called “Re-order.” You can then drag and drop the posts within according to the order you want them to appear in.

How does WP loop work?

The WordPress Loop is used by WordPress to publish content. In its simplest form, the WordPress Loop simply checks if there are posts or pages to be displayed and then displays them. By using multiple loops and modifying loops using the WP_Query class, theme developers can design complex website themes.


2 Answers

As documented at query_posts function page:

It is strongly recommended that you use the pre_get_posts filter instead, and alter the main query by checking is_main_query.

You can add a new action on pre_get_posts in your theme functions.php file, like:

function homepage_posts($query)
{
    if ($query->is_home() && $query->is_main_query())
    {
        $query->set( 'orderby', 'title' );
    }
}
add_action('pre_get_posts', 'homepage_posts');
like image 116
revo Avatar answered Oct 01 '22 22:10

revo


wp_reset_query() is the way to go

Example snippet

<?php query_posts(array('orderby'=>'title','order'=>'DESC'));

if ( have_posts() ) :
    while ( have_posts() ) : the_post(); ?>
        <a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
    endwhile;
endif;
wp_reset_query();

But keep in mind: query_posts() will change your main query and is not recommended. Only use if absolutely necessary (see query_posts: Caveats). Creating a new instance of WP_Query or get_posts() is preferred for secondary loops.

like image 42
Kevin Regenrek Avatar answered Oct 01 '22 20:10

Kevin Regenrek