WordPress: How To Sort Your Custom Post Type Posts Alphabetically | Martech Zone

WordPress: How To Sort Your Custom Post Type Posts Alphabetically | Martech Zone

With the new theme (and child theme) I’ve implemented on Martech Zone, I had to rebuild and recode the custom post type I built for Acronyms. I optimized the code to insert some additional custom fields and I’m having to redesign the archive and taxonomy templates to better display the acronyms listed.

Ecommerce Marketing Automation

In my last theme (whose developers discontinued support), these pages got quite a bit of attention because they were well-documented and even showed relevant articles to the acronym. I’ll continue to migrate that functionality to the new site and I even want to use a hover methodology to display the acronym definition rather than having the visitor click on the acronym link. Enough about that…

Custom Post Type Sorting

Because WordPress was originally designed for blog use, the default of any post type (including a custom post type) is to order the posts in reverse chronological order. While that works for news and articles, it’s not advantageous for things like a glossary or a list of acronyms. I want my acronyms to be ordered alphanumerically, not by the date that entered them in WordPress.

As with virtually every feature in WordPress, this can be easily customizable with the WordPress API. In my functions.php file in my child theme, I added the following code:

add_action( 'pre_get_posts', function ( $query ) {
	if ( $query->is_archive() && $query->is_main_query() ) { 
	  if ( get_query_var( 'post_type' ) == 'acronym' ) { 
		$query->set( 'order', 'ASC' );
		$query->set( 'orderby', 'title' );
} );

The pre_get_posts function is an action that is executed whenever posts are queried. In the code above, I’m able to ensure that any query for the custom post type of acronym is specifically set to be sorted by the title in ascending order.

This doesn’t just set this order in the output of the archive and taxonomy pages, it even orders the custom post type alphanumerically within the administrative panel of WordPress.

Because you’re setting the default query parameters, you can add other variables as well, like the number of records to retrieve (posts_per_page). For acronyms, I’m returning 25 records at a time where I’m defaulting to 10 on the rest of the site.

Custom post types can help you to significantly expand your site’s capabilities… and it can all be done with some simple code within your child theme (or core theme) without the need for any plugins. In fact, I recommend not using plugins since they often add computing overhead that may slow your site. I’m working on a client site right now where they’d like to incorporate job openings… and this code is going to come in handy for them as well!

Source link


Please enter your comment!
Please enter your name here