预计阅读时间: 3 分钟

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

用到的代码如下:


function add_custom_post_counts() {
    
    // 根据你的需要修改下面array()里面的文章类型别名即可
	$post_types = array( 'shop', 'docs' );
	foreach ( $post_types as $cpt ) {
		$cpt_info = get_post_type_object( $cpt );
		$num_posts = wp_count_posts( $cpt );
		$num = number_format_i18n( $num_posts->publish );
		$text = _n( $cpt_info->labels->singular_name, $cpt_info->labels->singular_name, intval( $num_posts->publish ) );
		echo '<li class="page-count '. esc_attr( $cpt_info->name ) . '-count"><a href="edit.php?post_type=' . esc_attr( $cpt ) . '">' . $num . ' ' . $text . '</a></li>';
	}
}
add_action( 'dashboard_glance_items', 'add_custom_post_counts' );

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

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

此文章对你有帮助吗? 已有 0 人说这篇文章是有用的。