Sortable Admin Columns for Custom Post Types in WordPress

/*-------------------------------------------------------------------------------
	Sortable Columns
-------------------------------------------------------------------------------*/

// add filter to output your heading titles = the names at the top where you sort
add_filter( 'manage_edit-customposttype_columns', 'my_edit_booksigning_columns' ) ;

function my_edit_booksigning_columns( $columns ) {

	$columns = array(
		'cb' => '<input type="checkbox" />',
		'title' => __( 'Book Signing Location' ),
		'startdate' => __( 'Book Signing Date' ),
		//'courselocation' => __( 'Book Signing Location' ),
		//'date' => __( 'Date' )
	);

	return $columns;
}


// action to pull in Advaced Custom Fields so you can sort by them
add_action( 'manage_book_customposttype_custom_column', 'my_manage_booksigning_columns', 10, 2 );

function my_manage_booksigning_columns( $column ) {
	global $post;

	
	if($column == 'startdate')
	{
		// Set some variables to set how to show the dates.
		$startdate = DateTime::createFromFormat('Ymd', get_field('date_of_signing'));
		
		echo $startdate->format('n - d') . " &raquo; " . $startdate->format('M d');
		
	}
	elseif($column == 'courselocation')
	{
		$location = get_field('location');
		echo $location;
	}
}


/*-------------------------------------------------------------------------------
	Sortable 
-------------------------------------------------------------------------------*/

function my_column_register_sortable( $columns )
{
	$columns['startdate'] = 'startdate';
	return $columns;
}

add_filter("manage_edit-customposttype_sortable_columns", "my_column_register_sortable" );


/* Only run our customization on the 'edit.php' page in the admin. */
add_action( 'load-edit.php', 'my_edit_booksigning_load' );

function my_edit_booksigning_load() {
	add_filter( 'request', 'my_sort_booksigning' );
}

/* Sorts the book_signings. */
function my_sort_booksigning( $vars ) {

	/* Check if we're viewing the 'book_signings' post type. */
	if ( isset( $vars['post_type'] ) && 'book_signings' == $vars['post_type'] ) {

		/* Check if 'orderby' is set to 'duration'. */
		if ( isset( $vars['orderby'] ) && 'startdate' == $vars['orderby'] ) {

			/* Merge the query vars with our custom variables. */
			$vars = array_merge(
				$vars,
				array(
					'meta_key' => 'date_of_signing',
					'orderby' => 'meta_value_num'
				)
			);
		}
	}

	return $vars;
}

 

Leave a Reply

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

52 + = 57