While it’s possible to sort the announcements on the dashboard by the dates by clicking on the column title, it sorts by the published date out of the box. This means that each time you want to sort the announcements by the announcement date then you’re forced to re-click the column heading, and waiting for the page the reload.

One of our users asked in the support forum if it was possible to load this table sorted by the announcement date, so they didn’t have to constantly re-sort the table on every page load.

We thought that this was a great question and something that many of our users might be interested in implementing. So we went ahead and threw together a code snippet that you can add to your themes functions.php file or into a custom MU plugin.

Snippet

/**
 * Sort the Timeline Express announcements by announcement date on the dashboard
 * @see https://wordpress.org/support/topic/announcement-list-order/
 *
 * @param object $query Query object.
 */
function timeline_express_announcements_sort_by_date( $query ) {

	if ( ! is_admin() || ! $query->is_main_query() ) {

		return;

	}

	$screen = get_current_screen();

	if ( ! isset( $screen->post_type ) || 'te_announcements' !== $screen->post_type || isset( $_GET['orderby'] ) ) {

		return;

	}

	$query->set( 'meta_key', 'announcement_date' );
	$query->set( 'orderby', 'meta_value_num' );
	$query->set( 'order', 'ASC' ); // Possible: ASC/DESC

}
add_action( 'pre_get_posts', 'timeline_express_announcements_sort_by_date' );

Parameters:

  • meta_key: The meta value to sort the announcements by. This can be altered to sort by a different value, such as the announcement_color or announcement_icon, or a custom value if you’ve added additional meta to the announcement post type.
  • orderby: How to calculate the sort order. If this is a number, as in the case of the announcement_date, you’ll want to use meta_value_num else you’ll want to use meta_value for alphabetical sort order.
  • order: This can be ASC for an ascending sort order, or DESC for descending sort order.
  • Note: These are not the only values you can specify. For additional parameters, take a look at the Codex article for the WP_Query class and for the action pre_get_posts.

    The code snippet above will load the announcements table and sort them by announcement date in ascending order, but will still allow you to sort the table by another value if you choose to. You’ll still be able to sort the table by the published date or alphabetically by the announcement name by clicking on any of the column headings.

    Once added to your themes functions.php file or into a custom MU plugin you can save the file, and check to confirm that the announcements now load in the order you need.

    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.