在自定义帖子类型列中显示自定义分类

时间:2014-11-04 18:57:45

标签: php wordpress custom-post-type taxonomy

我查看过有关向CPT列添加自定义分类的几篇帖子;除了实际显示所述分类法(出版物)之外,我能够使一切正常。这是我的CPT代码:

add_action( 'init', 'pb_custom_post_type' );
function pb_custom_post_type() {
  $labels = array(
  'name'               => _x( 'Press', 'post type general name' ),
  'singular_name'      => _x( 'Press', 'post type singular name' ),
  'add_new'            => _x( 'Add New', 'review' ),
  'add_new_item'       => __( 'Add New Press' ),
  'edit_item'          => __( 'Edit Press' ),
  'new_item'           => __( 'New Press' ),
  'all_items'          => __( 'All Press' ),
  'view_item'          => __( 'View Press' ),
  'search_items'       => __( 'Search Press' ),
  'not_found'          => __( 'No press found' ),
  'not_found_in_trash' => __( 'No press found in the Trash' ), 
  'parent_item_colon'  => '',
  'menu_name'          => 'Press'
);
  $args = array(
  'labels'        => $labels,
  'description'   => 'Press information',
  'public'        => true,
  'menu_position' => 20,
  'supports'      => array( 'title', 'editor', 'thumbnail' ),
  'has_archive'   => true,
);
  register_post_type( 'press', $args ); 
}

add_filter( 'manage_edit-press_columns', 'my_edit_press_columns' ) ;
function my_edit_press_columns( $columns ) {
  $columns = array(
    'cb' => '<input type="checkbox" />',
    'title' => __( 'Title' ),
    'publication' => __( 'Publication' ),
    'date' => __( 'Date' )
  );

  return $columns;
}

自定义分类

add_action( 'init', 'create_my_taxonomies', 0 );
function create_my_taxonomies() {
    register_taxonomy( 'publication', 'press', array( 'hierarchical' => false, 'label' => 'Publications', 'query_var' => false, 'rewrite' => true ) );
}

现在我已经看到了两种不同的选择,要么尝试在分类法参数中添加show_ui / show_admin_column,要么在switch语句中使用另一个函数。我已经在下面尝试了,是否有一些我不知道的重要事项?

1

add_action( 'init', 'create_my_taxonomies', 0 );
function create_my_taxonomies() {
  $args = array (   
    'show_ui'           => true,
    'show_admin_column' => true,
  );
   register_taxonomy( 'publication', 'press', array( 'hierarchical' => false, 'label' => 'Publications', 'query_var' => false, 'rewrite' => true ), $args );
}

2

function custom_columns( $column, $post_id ) {
  switch ( $column ) {
    case "publication":
      echo get_post_meta( $post_id, 'publication', true);
      break;
  }
}
add_action( "manage_posts_custom_column", "custom_columns", 10, 2 );

1 个答案:

答案 0 :(得分:1)

删除自定义列函数,并将'show_admin_column' => true添加到register_taxonomy的实际args数组中:

register_taxonomy( 'publication', 'press', array( 'show_admin_column' => true, 'hierarchical' => false, 'label' => 'Publications', 'query_var' => false, 'rewrite' => true ) );

修改:您可能还想将'taxonomies' => array( 'publication' )添加到register_post_type args。