After writing my previous post where I alphabetize all categories site wide except the ‘news-events’ slug it seemed appropriate to do the same thing as a very simplified plugin. Everything from that post remains the same except I’ve added a plugin header to provide information to WordPress about the plugin.

<?php
/*
Plugin Name:  Alphabetize All Categories Except News & Events
Plugin URI:   https://joseph-dickson/alphabetize-all-categories-except-news-events-plugin
Description:  This will set all categories to display in alphbetical order except a category slugged 'news-events'
Version:      20180824
Author:       Joseph Dickson
Author URI:   https://joseph-dickson.com/
License:      GPL2
License URI:  https://www.gnu.org/licenses/gpl-2.0.html
Text Domain:  alphabetize-all-categories-except-news-events
Domain Path:  /languages
*/

// Block direct access to PHP file
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

/*
 * Order news-events by descending order
 * All other archives are ordered by title alphabetically
 */
add_action( 'pre_get_posts', 'joseph_dickson_change_sort_order');
function joseph_dickson_change_sort_order($query){

	if(is_category('news-events')) {

		// Set the order to DESC descending
		$query->set( 'order', 'DESC' );

		// Set the orderby date so it loops newest to oldest posts
		$query->set( 'orderby', 'post_date' );

	}

	elseif( !is_category( 'news-events' )) {

		//Set the order ASC ascending
		$query->set( 'order', 'ASC' );

		//Set the orderby title so it loops A-Z
		$query->set( 'orderby', 'title' );

	}

};

Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.