In this tutorial, i’ll give you several PHP code snippets i have tested locally which enable you to customize how your posts are displayed on any archive.
Modify this code at the end of your child themes functions.php file according to your own needs.
A reader asked: I need to change the order of posts being displayed on a category archive page. I need them to be oldest first.
Note: These code snippets will work in any WordPress theme.
Custom Post Type Archive Page
This code display 6 posts per page from a custom post type named portfolio with the most recent post displayed first.
add_action( 'pre_get_posts', 'custom_post_type_archive' );
function custom_post_type_archive( $query ) {
if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'portfolio' ) ) {
$query->set( 'posts_per_page', '6' );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'DESC' );
}
}
Category Archive Page
This PHP code displays the oldest post first and only 1 post per archive page.
function conditional_custom_category_limit( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
if ( is_archive(category-i.d) ) {
$query->set( 'posts_per_page', 1 );
$query->set( 'orderby', 'title' );
$query->set( 'order', 'ASC' );
return;
}
}
add_action( 'pre_get_posts', 'conditional_custom_category_limit', 1 );
Simply replace the category-i.d with your actual category i.d or category permalink slug.
Limit Posts Per Category Archive Page
This line in the code above enables you to control how many posts display on any archive page:
$query->set( 'posts_per_page', 1 );
Simply change the 1 to any number you like.
Order Newest or Oldest Posts First
This line in the code above enables you to control which posts are displayed first. You can use ASC or DESC for newest or oldest posts first:
$query->set( 'order', 'ASC' );
Simply change the ASC to DESC and vice versa.
Source http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts
Was This Tutorial Helpful?