华纳云香港服务器

WordPress钩子manage_posts_custom_column的介绍及使用

WordPress主题推荐

WordPress 后台所有文章的列表中所显示的列都是固定的,如果想要自定义一些列,如增加一列文章的修改时间等,则需要用到 manage_posts_custom_column 钩子了,这就是本文的重点内容。

WordPress钩子manage_posts_custom_column的介绍及使用-第1张-boke112百科(boke112.com)

manage_posts_custom_column 钩子的介绍

在文章列表中的每个自定义列中触发。

do_action( 'manage_posts_custom_column', string $column_name, int $post_id )

仅当当前帖子类型为 post 文章(含自定义文章类型)时,才会触发此挂钩。

参数:

  • $column_name:(string)要显示的列的名称。
  • $post_id:(int) 当前帖子 ID。

钩子所在文件:wp-admin/includes/class-wp-posts-list-table.php

manage_posts_custom_column 钩子的使用示例

示例:显示自定义帖子类型: 假设您具有“图书”自定义帖子类型,并且希望“出版商”和“图书作者”显示在浏览页面中。

function custom_columns( $column, $post_id ) {
switch ( $column ) {
case 'book_author':
$terms = get_the_term_list( $post_id, 'book_author', '', ',', '' );
if ( is_string( $terms ) ) {
echo $terms;
} else {
_e( 'Unable to get author(s)', 'your_text_domain' );
}
break;

case 'publisher':
echo get_post_meta( $post_id, 'publisher', true ); 
break;
}
}
add_action( 'manage_posts_custom_column' , 'custom_columns', 10, 2 );

示例:在所有文章列表中增加一列置顶文章

 /* 显示置顶文章自定义列 */
function display_posts_stickiness( $column, $post_id ) {
if ($column == 'sticky'){
echo '<input type="checkbox" disabled', ( is_sticky( $post_id ) ? ' checked' : ''), '/>';
}
}
add_action( 'manage_posts_custom_column' , 'display_posts_stickiness', 10, 2 );

/* 在所有文章列表中增加 1 列置顶文章 */
function add_sticky_column( $columns ) {
return array_merge( $columns, 
array( 'sticky' => __( 'Sticky', 'boke112.com' ) ) );

以上内容整理自@WordPress – manage_posts_custom_column

示例:在所有文章列表中增加一列修改时间,详见『如何为 WordPress 后台所有文章列表添加一列修改时间?』。

本文地址:https://boke112.com/post/4287.html

赞 (0) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu