为 bbPress 管理后台添加管理员小工具/Admin Widget,向 WordPress 仪表盘添加两个小工具:一个显示在线用户列表,另一个显示最新主题和回复列表。

把下面的代码复制到主题 functions.php 中:
<?php
// Add bbPress Dashboard Widgets
add_action('wp_dashboard_setup', 'bbpress_dashboard_widgets');
function bbpress_dashboard_widgets() {
// Only load if bbPress is active
if (class_exists('bbPress')) {
wp_add_dashboard_widget(
'bbp_online_users_widget',
__('Online Users', 'text-domain'),
'bbp_online_users_widget_content'
);
wp_add_dashboard_widget(
'bbp_recent_activity_widget',
__('Recent Forum Activity', 'text-domain'),
'bbp_recent_activity_widget_content'
);
}
}
// Online Users Widget Content
function bbp_online_users_widget_content() {
$online_users = bbp_get_online_users();
if (empty($online_users)) {
echo '<p>' . __('No users currently online.', 'text-domain') . '</p>';
return;
}
echo '<ul>';
foreach ($online_users as $user_id) {
$user = get_userdata($user_id);
printf(
'<li><a href="%s">%s</a></li>',
esc_url(get_author_posts_url($user_id)),
esc_html($user->display_name)
);
}
echo '</ul>';
}
// Recent Activity Widget Content
function bbp_recent_activity_widget_content() {
// Recent Topics
$topic_query = new WP_Query(array(
'post_type' => bbp_get_topic_post_type(),
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC'
));
if ($topic_query->have_posts()) {
echo '<h4>' . __('Recent Topics', 'text-domain') . '</h4>';
echo '<ul>';
while ($topic_query->have_posts()) {
$topic_query->the_post();
printf(
'<li><a href="%s">%s</a> (%s)</li>',
esc_url(bbp_get_topic_permalink()),
esc_html(bbp_get_topic_title()),
esc_html(get_the_date())
);
}
echo '</ul>';
wp_reset_postdata();
}
// Recent Replies
$reply_query = new WP_Query(array(
'post_type' => bbp_get_reply_post_type(),
'posts_per_page' => 5,
'orderby' => 'date',
'order' => 'DESC'
));
if ($reply_query->have_posts()) {
echo '<h4>' . __('Recent Replies', 'text-domain') . '</h4>';
echo '<ul>';
while ($reply_query->have_posts()) {
$reply_query->the_post();
printf(
'<li><a href="%s">%s</a> (%s)</li>',
esc_url(bbp_get_reply_url()),
esc_html(get_the_title()),
esc_html(get_the_date())
);
}
echo '</ul>';
wp_reset_postdata();
}
}
// Helper: Get online users
function bbp_get_online_users() {
$users = array();
$logged_in_users = get_transient('online_status');
if (!is_array($logged_in_users)) return $users;
$online_threshold = 15 * 60; // 15 minutes in seconds
$current_time = current_time('timestamp');
foreach ($logged_in_users as $user_id => $last_activity) {
if (($current_time - $last_activity) < $online_threshold) {
$users[] = $user_id;
}
}
return $users;
}
?>