是的,您在列表上方看到的处于各种状态的页面计数是通过运行获得的wp_count_posts
但表中的页面是通过运行WP_Query
这两件事unrelated.
如果还想修改计数,则还必须过滤wp_count_posts
使用\'wp_count_posts\'
过滤器挂钩。
此外,您还应该检查要从编辑中排除的页面的状态,因为wp_count_posts
分别统计所有状态。
因此,我们有两项任务:
从查询中删除页面从计数中删除页面我将为这两个任务编写两个函数,在这两个函数中,我需要检查我们是否在管理中,当前用户是否具有所需的功能,最后检查当前屏幕是否正确。我将编写一个执行这些检查的附加函数,以避免重复编写相同的代码:
function in_pages_edit() {
if ( ! is_admin() || ! current_user_can( \'edit_pages\' ) ) return FALSE;
$s = get_current_screen();
return ( $s instanceof WP_Screen && $s->id === \'edit-page\' );
}
现在我们可以为out 2个任务添加2个挂钩,我将在
\'load-edit.php\'
措施:
function go_exclude_pages_from_edit() {
if ( ! in_pages_edit() ) return;
global $exclude_pages_from_edit;
$exclude_pages_from_edit = array( 662 ); // <-- set here the page ids to exclude
add_filter( \'wp_count_posts\', \'change_pages_count\', 10, 3 );
add_action( \'pre_get_posts\', \'exclude_pages_from_edit\' );
}
add_action( \'load-edit.php\', \'go_exclude_pages_from_edit\' );
现在,我们可以从查询中删除页面:
function exclude_pages_from_edit( $query ) {
if ( ! in_pages_edit() || ! $query->is_main_query() ) return;
global $exclude_pages_from_edit;
if ( ! empty($exclude_pages_from_edit) ) {
$query->set( \'post__not_in\', $exclude_pages_from_edit );
}
}
并调整计数(有关解释,请参阅内联注释):
function get_valid_page_from_post( $p ) {
if ( $p instanceof WP_Post && $p->post_type === \'page\' ) return $p;
}
function change_pages_count( $counts, $type, $perm ) {
// do nothing if not on right page
if ( ! in_pages_edit() || $type !== \'page\' ) return $counts;
// do the work only once
static $new_counts;
if ( ! is_null( $new_counts ) ) return $new_counts;
global $exclude_pages_from_edit;
// get the pages objects and be sure they are valid pages
$excluded = array_filter(
array_map( \'get_post\', $exclude_pages_from_edit ), \'get_valid_page_from_post\'
);
// if no page object obtained do nothing
if ( empty( $excluded ) ) return $counts;
// count the statuses of the page objectt
$statuses_excluded = array_count_values ( wp_list_pluck( $excluded, \'post_status\' ) );
// subtract from each status count the excluded pages status count
foreach ( $statuses_excluded as $status => $num ) {
if ( isset( $counts->$status ) ) {
$counts->$status = (string) $counts->$status - $num;
}
}
// save the ajusted count for next running and return
$new_counts = $counts;
return $counts;
}