Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Last active May 28, 2019 02:39
Show Gist options
  • Save MogulChris/b348ccc15ed6fef3cf4b50e03eca3a07 to your computer and use it in GitHub Desktop.
Save MogulChris/b348ccc15ed6fef3cf4b50e03eca3a07 to your computer and use it in GitHub Desktop.
Wordpress - add custom columns to the listing pages for one or post types
<?php
//easy way to cover multiple post types, including custom ones
foreach(['page','post','custom_post_type'] as $content_type){
add_filter( 'manage_' . $content_type . '_posts_columns', 'mytheme_custom_column' );
add_action( 'manage_' . $content_type . '_posts_custom_column', 'mytheme_custom_column_values', 10, 2);
add_filter( 'manage_edit-' . $content_type . '_sortable_columns', 'mytheme_custom_column_sorting' );
}
//column label
function mytheme_custom_column($columns){
$columns['custom_column_name'] = 'My column'; //the label above the column in the listing
return $columns;
}
//column value
function mytheme_custom_column_values($column, $post_id){
if($column == 'custom_column_name'){
//get the value for your column from $post_id, eg get_post_meta() or get_field() if using ACF
echo get_post_meta($post_id, 'some_meta_field',true);
}
}
//column sorting
function mytheme_custom_column_sorting($columns){
$columns['custom_column_name'] = '_custom_orderby_value'; //_custom_orderby_value can be a real 'orderby' value for WP_Query, but in this case it's a placeholder which we will intercept before it is used.
return $columns;
}
//intercept WP_Queries and check for our placeholder 'orderby' value
//Note pre_get_posts is used a *lot*, so quickly check if this is the query you want and bail early if not
function mytheme_orderby( $query ) {
if( ! is_admin() ) return; //bail if we are not on the back end
$orderby = $query->get( 'orderby');
if( $orderby == '_custom_orderby_value' ) { //found the query we want to modify
//you can do what you want in here with WP_Query parameters
//I will just specify a meta field and order it numerically
$query->set('meta_key','some_meta_field'); //the meta field we want to sort on
$query->set('orderby','meta_value_num'); //a 'real' orderby value (one of the allowed ones for wp_query)
}
}
add_action('pre_get_posts', 'mytheme_orderby');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment