WordPress 的自定義文章類型是非常好的一個功能,允許我們根據(jù)需求創(chuàng)建和文章等類似的文章類型,每種文章類型都有自己的管理菜單和功能。如果你的網(wǎng)站擁有自定義文章類型,你肯定希望可以向文章、頁面和評論一樣,在儀表盤的【概覽】小工具顯示其他文章類型的數(shù)據(jù),如下圖所示:

這就是WordPress大學(xué)今天要分享的教程:如何在WordPress后臺儀表盤“概覽”小工具添加其他文章類型數(shù)據(jù)。
用到的代碼如下:
function wpdaxue_add_custom_post_counts() {
// 根據(jù)你的需要修改下面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', 'wpdaxue_add_custom_post_counts' );
以上代碼是通過將功能掛載到 dashboard_glance_items 鉤子來實(shí)現(xiàn)需求的。你只需要根據(jù)自己的實(shí)際情況,修改第四行代碼的 array() 數(shù)組的文章類型別名,然后添加到當(dāng)前主題的 functions.php 即可。
如果你要查看文章類型的值,可以在后臺點(diǎn)擊對應(yīng)文章類型導(dǎo)航菜單下的第一個子菜單,比如頁面-全部頁面,就可以在網(wǎng)址中看到?/wp-admin/edit.php?post_type=page,其中?post_type=?后面的值,就是文章類型的值了,比如頁面就是?page。




