danzo
danzo

Reputation: 301

Adding column to WordPress admin for posts only, not custom post types

I've added some code to my WP site that counts how many times a post has been viewed. I then added a column in the admin to show how many views the post has received. This is for standard WP blog posts:

// SHOW POST VIEWS COLUMN IN ADMIN...
add_filter('manage_posts_columns', 'posts_column_views');
add_action('manage_posts_custom_column', 
'posts_custom_column_views',5,2);
function posts_column_views($defaults){

$defaults['post_views'] = __('Views');
return $defaults;
}
function posts_custom_column_views($column_name, $id){

if($column_name === 'post_views'){
    echo my_get_post_views(get_the_ID());
    }
}

This works fine, but the problem is that now this new column shows in all the custom post types as well. I wrote some code to unset it from the custom post types (see below) which works fine.

// BUT DON'T SHOW IT ON CUSTOM POST TYPES
function jxb_manage_columns( $columns ) {
  unset($columns['post_views']);
  return $columns;
}

function jxb_column_init() {
  add_filter( 'manage_jxb-component_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_faqs_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_edr-component_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_new-stories_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_loc_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_upcoming-event_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_product-return_posts_columns' , 'jxb_manage_columns' );
  add_filter( 'manage_splash-page_posts_columns' , 'jxb_manage_columns' );
}
add_action( 'admin_init' , 'jxb_column_init' );

Just wondering if there is a more efficient way to do this rather than to unset the column from each custom post type individually. Thanks!

Upvotes: 2

Views: 2586

Answers (1)

caiovisk
caiovisk

Reputation: 3809

By the WordPress codex documentation you can set the post type name on the filter manage_{$post_type}_posts_columns, see CODEX

So you can set the post (which is actually a post type) on {$post_type} then you will limit your filter to the post post types, so:

add_filter('manage_post_posts_columns', 'posts_column_views');
add_action('manage_post_posts_custom_column', 'posts_custom_column_views',5,2);

Upvotes: 6

Related Questions