WordPress后台仪表盘“概览”小工具添加其他文章类型数据

资讯1年前 (2023)发布 iowen
118 0 0

WordPress 的自定义文章类型是非常好的一个功能,允许我们根据需求创建和文章等类似的文章类型,每种文章类型都有自己的管理菜单和功能。如果你的网站拥有自定义文章类型,你肯定希望可以向文章、页面和评论一样,在仪表盘的【概览】小工具显示其他文章类型的数据,如下图所示:

这就是WordPress大学今天要分享的教程:如何在WordPress后台仪表盘“概览”小工具添加其他文章类型数据。

用到的代码如下:

  1. function wpdaxue_add_custom_post_counts() {

  2. // 根据你的需要修改下面array()里面的文章类型别名即可

  3. $post_types = array( 'shop', 'docs' );


  4. foreach ( $post_types as $cpt ) {

  5. $cpt_info = get_post_type_object( $cpt );

  6. $num_posts = wp_count_posts( $cpt );

  7. $num = number_format_i18n( $num_posts->publish );

  8. $text = _n( $cpt_info->labels->singular_name, $cpt_info->labels->singular_name, intval( $num_posts->publish ) );


  9. echo '<li class="page-count '. esc_attr( $cpt_info->name ) . '-count"><aborder-width: 0px;border-style: initial;border-color: initial;font-family: inherit;font-style: inherit;font-weight: inherit;outline: 0px;vertical-align: baseline;overflow-wrap: break-word;box-sizing: border-box;color: rgb(230, 233, 237);"> . esc_attr( $cpt ) . '">' . $num . ' ' . $text . '</a></li>';

  10. }

  11. }

  12. add_action( 'dashboard_glance_items', 'wpdaxue_add_custom_post_counts' );

以上代码是通过将功能挂载到 dashboard_glance_items 钩子来实现需求的。你只需要根据自己的实际情况,修改第四行代码的 array() 数组的文章类型别名,然后添加到当前主题的 functions.php 即可。

如果你要查看文章类型的值,可以在后台点击对应文章类型导航菜单下的第一个子菜单,比如页面-全部页面,就可以在网址中看到 /wp-admin/edit.php?post_type=page,其中 post_type= 后面的值,就是文章类型的值了,比如页面就是 page


© 版权声明

相关文章

暂无评论

暂无评论...