WP+WPML场景下,edit.php仅显当前用户文章并修正筛选计数
解决WordPress后台edit.php页面WPML环境下文章计数不符问题
你当前的代码已经实现了非管理员用户仅查看自己的文章,但后台筛选栏的计数未同步适配——原因是默认的文章计数查询没有应用作者筛选规则,且WPML会统计所有语言的所有用户文章。以下是修正方案:
保留原有列表筛选代码
继续使用你已有的pre_get_posts代码,确保文章列表正确显示当前用户的内容:
function posts_for_current_author($query) { global $pagenow; if( 'edit.php' != $pagenow || !$query->is_admin ){ return $query; } if( !current_user_can( 'manage_options' ) ) { global $user_ID; $query->set('author', $user_ID ); } return $query; } add_filter('pre_get_posts', 'posts_for_current_author');
添加计数修正代码
将以下代码添加到子主题functions.php中,修改后台文章计数逻辑,让非管理员用户的筛选栏计数仅统计自己的所有语言文章:
// 修正WPML环境下后台文章筛选计数 function custom_post_count_for_current_author($counts, $type, $perm) { global $pagenow, $user_ID; // 仅在文章列表后台页生效,且当前用户不是管理员 if ('edit.php' !== $pagenow || current_user_can('manage_options')) { return $counts; } // 仅处理文章类型(如需适配自定义文章类型,可修改或移除此判断) if ('post' !== $type) { return $counts; } // 查询当前用户所有语言的文章 $args = array( 'author' => $user_ID, 'post_type' => $type, 'post_status' => array('publish', 'draft', 'pending', 'future', 'private', 'trash'), 'posts_per_page' => -1, 'suppress_filters' => false, // 保留WPML过滤器,统计所有语言版本 ); $query = new WP_Query($args); $status_counts = array(); // 统计各状态文章数量 foreach ($query->posts as $post) { $status = $post->post_status; $status_counts[$status] = isset($status_counts[$status]) ? $status_counts[$status] + 1 : 1; } // 整理为WP默认计数格式 $counts = new stdClass(); $counts->publish = $status_counts['publish'] ?? 0; $counts->draft = $status_counts['draft'] ?? 0; $counts->pending = $status_counts['pending'] ?? 0; $counts->future = $status_counts['future'] ?? 0; $counts->private = $status_counts['private'] ?? 0; $counts->trash = $status_counts['trash'] ?? 0; $counts->total = array_sum((array)$counts); return $counts; } add_filter('wp_count_posts', 'custom_post_count_for_current_author', 10, 3);
代码说明
wp_count_posts过滤器直接修改后台显示的文章计数,仅对非管理员用户在edit.php页面生效- 查询参数中
suppress_filters => false确保WPML的语言筛选逻辑生效,统计当前用户所有语言的文章 - 代码会按文章状态(发布、草稿、待审等)分别统计数量,确保筛选栏各状态的计数都准确
添加完成后,刷新后台文章列表页,“全部”筛选的计数会与实际显示的当前用户文章总数一致,各状态的计数也会同步修正。
内容的提问来源于stack exchange,提问作者Viktoras
相关产品推荐
相关产品推荐

