Altering archive orderby or posts-per-page on custom post type

On a project recently, I was using a custom post type for locations. These consisted of places, cities and districts as a non-hierarchial cpt. Running the archive of the post type on a standard archive.php file naturally lists the posts in order of publish date – most recent displayed first.   The archive also took into account the limit set in the admin under Settings > Reading, where I had set the posts per page to 9, as all my other archives were in a grid format. I needed to alter these 2 values just for this cpt archive alone.  Here’s how:

Add this to your functions.php file, or in a standalone plugin:

function owen_posts_per_page($query) {
if ( is_post_type_archive('locations') ) {  // set to my cpt, locations
$query->set('posts_per_page', -1);  // this sets the posts per page
$query->set( 'order', 'ASC' ); // sets ascending order
$query->set( 'orderby', 'title' ); // sets alphabetical order
add_action('pre_get_posts', 'owen_posts_per_page');


You can add more parameters for loops in here using the ‘$query->set( ‘key’, ‘value’ );’.  Hope that helps!

Useful post? Share it

Leave a Reply

Your email address will not be published. Required fields are marked *