Добавление счетчиков пользовательских типов записей в админ-панель WordPress
В админ-панели WordPress удобно отображается количество записей, страниц и комментариев. Я хочу, чтобы там также показывалось количество статей, видео и мультфильмов (три пользовательских типа записей, зарегистрированных в моей теме). Как можно добавить эти счетчики в виджет "Прямо сейчас" на главной странице админ-панели?

Да, в этом виджете есть несколько действий, включая right_now_content_table_end
. Пример:
function my_right_now() {
// Получаем количество публикаций типа 'widget'
$num_widgets = wp_count_posts( 'widget' );
// Форматируем число и получаем правильную форму слова
$num = number_format_i18n( $num_widgets->publish );
$text = _n( 'Виджет', 'Виджеты', $num_widgets->publish );
// Если пользователь может редактировать страницы, делаем ссылки
if ( current_user_can( 'edit_pages' ) ) {
$num = "<a href='edit.php?post_type=widget'>$num</a>";
$text = "<a href='edit.php?post_type=widget'>$text</a>";
}
// Выводим строку таблицы
echo '<tr>';
echo '<td class="first b b_pages">' . $num . '</td>';
echo '<td class="t pages">' . $text . '</td>';
echo '</tr>';
}
// Добавляем нашу функцию к действию
add_action( 'right_now_content_table_end', 'my_right_now' );

Также рассматривается в лучшей коллекции Wiki: http://wordpress.stackexchange.com/questions/1567/best-collection-of-code-for-your-functions-php-file

На основе этого же кода, вы можете использовать следующее для отображения количества всех пользовательских типов записей и таксономий:
// Добавляем счетчики пользовательских таксономий и типов записей в консоль
add_action( 'right_now_content_table_end', 'my_add_counts_to_dashboard' );
function my_add_counts_to_dashboard() {
// Счетчики пользовательских таксономий
$taxonomies = get_taxonomies( array( '_builtin' => false ), 'objects' );
foreach ( $taxonomies as $taxonomy ) {
$num_terms = wp_count_terms( $taxonomy->name );
$num = number_format_i18n( $num_terms );
$text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name, $num_terms );
$associated_post_type = $taxonomy->object_type;
if ( current_user_can( 'manage_categories' ) ) {
$num = '<a href="edit-tags.php?taxonomy=' . $taxonomy->name . '&post_type=' . $associated_post_type[0] . '">' . $num . '</a>';
$text = '<a href="edit-tags.php?taxonomy=' . $taxonomy->name . '&post_type=' . $associated_post_type[0] . '">' . $text . '</a>';
}
echo '<td class="first b b-' . $taxonomy->name . 's">' . $num . '</td>';
echo '<td class="t ' . $taxonomy->name . 's">' . $text . '</td>';
echo '</tr><tr>';
}
// Счетчики пользовательских типов записей
$post_types = get_post_types( array( '_builtin' => false ), 'objects' );
foreach ( $post_types as $post_type ) {
$num_posts = wp_count_posts( $post_type->name );
$num = number_format_i18n( $num_posts->publish );
$text = _n( $post_type->labels->singular_name, $post_type->labels->name, $num_posts->publish );
if ( current_user_can( 'edit_posts' ) ) {
$num = '<a href="edit.php?post_type=' . $post_type->name . '">' . $num . '</a>';
$text = '<a href="edit.php?post_type=' . $post_type->name . '">' . $text . '</a>';
}
echo '<td class="first b b-' . $post_type->name . 's">' . $num . '</td>';
echo '<td class="t ' . $post_type->name . 's">' . $text . '</td>';
echo '</tr>';
if ( $num_posts->pending > 0 ) {
$num = number_format_i18n( $num_posts->pending );
$text = _n( $post_type->labels->singular_name . ' ожидает', $post_type->labels->name . ' ожидают', $num_posts->pending );
if ( current_user_can( 'edit_posts' ) ) {
$num = '<a href="edit.php?post_status=pending&post_type=' . $post_type->name . '">' . $num . '</a>';
$text = '<a href="edit.php?post_status=pending&post_type=' . $post_type->name . '">' . $text . '</a>';
}
echo '<td class="first b b-' . $post_type->name . 's">' . $num . '</td>';
echo '<td class="t ' . $post_type->name . 's">' . $text . '</td>';
echo '</tr>';
}
}
}

Для тех, кто хочет изменить раздел "Обсуждение", чтобы отображать количество ожидающих публикации записей вместо того, чтобы показывать всё в "контенте", можно использовать хук right_now_discussion_table_end следующим образом:
add_action( 'right_now_discussion_table_end', 'my_add_counts_to_rightnow_discussion' );
function my_add_counts_to_rightnow_discussion() {
// Количество записей для пользовательских типов записей
$post_types = get_post_types( array( '_builtin' => false, 'public' => true , 'show_ui' => true), 'objects' );
foreach ( $post_types as $post_type ) {
if ( current_user_can( 'edit_posts' ) ) {
$num_posts = wp_count_posts( $post_type->name );
$text = _n( $post_type->labels->singular_name, $post_type->labels->name, $num_posts->publish );
$num = number_format_i18n( $num_posts->pending );
$post_types = get_post_types( array( '_builtin' => false, 'public' => true , 'show_ui' => true), 'objects' );
$num = '<a href="edit.php?post_status=pending&post_type=' . $post_type->name . '">' . $num . '</a>';
$text = '<a class="waiting" href="edit.php?post_status=pending&post_type=' . $post_type->name . '">' . $text . ' Ожидают </a>';
echo '<td class="first b b-' . $post_type->name . 's">' . $num . '</td>';
echo '<td class="t ' . $post_type->name . 's">' . $text . '</td>';
echo '</tr>';
}
}
}
Я также убрал условие if(pending >0)
, чтобы типы записей выравнивались с количеством слева. Если вы используете этот код, просто возьмите код Sébastien или Adam для подсчётов и удалите раздел с ожидающими записями.
Также обратите внимание, что я добавил проверку на то, являются ли типы записей публичными и отображаются ли в интерфейсе. Это можно добавить в любой из других кодов.

add_action( 'dashboard_glance_items', 'cor_right_now_content_table_end' );
function cor_right_now_content_table_end() {
$args = array(
'public' => true,
'_builtin' => false
);
$output = 'object';
$operator = 'and';
// Получаем все пользовательские типы записей
$post_types = get_post_types( $args, $output, $operator );
foreach ( $post_types as $post_type ) {
$num_posts = wp_count_posts( $post_type->name );
$num = number_format_i18n( $num_posts->publish );
// Используем _n() для правильного склонения (единственное/множественное число)
$text = _n( $post_type->labels->singular_name, $post_type->labels->name, intval( $num_posts->publish ) );
if ( current_user_can( 'edit_posts' ) ) {
$output = '<a href="edit.php?post_type=' . $post_type->name . '">' . $num . ' ' . $text . '</a>';
}
echo '<li class="post-count ' . $post_type->name . '-count">' . $output . '</li>';
}
// Получаем все пользовательские таксономии
$taxonomies = get_taxonomies( $args, $output, $operator );
foreach ( $taxonomies as $taxonomy ) {
$num_terms = wp_count_terms( $taxonomy->name );
$num = number_format_i18n( $num_terms );
$text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name, intval( $num_terms ) );
if ( current_user_can( 'manage_categories' ) ) {
$output = '<a href="edit-tags.php?taxonomy=' . $taxonomy->name . '">' . $num . ' ' . $text . '</a>';
}
echo '<li class="taxonomy-count ' . $taxonomy->name . '-count">' . $output . '</li>';
}
}
// Добавляем пользовательские CSS стили для виджета "Обзор"
function custom_colors() {
echo '<style type="text/css">
.slides-count a:before {content:"\f233"!important} /* Иконка для слайдов */
.gallery-count a:before {content:"\f163"!important} /* Иконка для галерей */
</style>';
}
add_action('admin_head', 'custom_colors');
