• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP SITES

2665

Original Genesis Tutorials & 5000+ Guaranteed Code

Snippets

  • Support
  • Newsletter
  • Videos
  • Log in

Premium Member? - Request custom code

Customize Archive Pages Conditionally Using Pre Get Posts

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

Related Solutions

  • Set Post & Content Limits For Home, Blog & Archive Pages
  • Add Custom Post Type (CPT) Pages To Posts Page

pre_get_posts

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Primary Sidebar

PHP Code

template_include

get_body_class

if else

array

class_exists

foreach

sprintf

add_action

printf

variable

Advertise · WPEngine · Genesis · Log in

  • How Premium Membership Works
  • Sign Up
  • Support
  • Subscription Details/Invoice
  • Tagged Tutorials
  • Access-Download Problems