You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用钩子修改WordPress核心class-wp-list-table.php的pagination函数HTML

修改WordPress自定义文章类型列表分页显示文本的实现方案

核心原则:绝不修改核心文件

直接改动wp-admin/includes/class-wp-list-table.php会导致WordPress更新后代码丢失,必须通过钩子实现需求。

实现方案一:用admin_footer钩子结合JavaScript修改DOM

由于WP_List_Table的pagination()函数未直接暴露钩子,最稳妥的方式是在后台页面加载完成后,动态替换目标文本:

add_action('admin_footer', 'custom_cpt_pagination_display');
function custom_cpt_pagination_display() {
    // 替换为你的自定义文章类型slug,比如'product'
    $target_cpt = 'your_cpt_slug';
    $current_screen = get_current_screen();
    
    // 仅在目标CPT的列表页执行
    if (isset($current_screen->id) && $current_screen->id === "edit-{$target_cpt}") {
        global $wp_query;
        $page = get_query_var('paged') ?: 1;
        $ppp = get_query_var('posts_per_page');
        $total_items = $wp_query->found_posts;
        $end = min($ppp * $page, $total_items);
        $start = $end - $ppp + 1;
        // 处理总数量不足一页的情况
        if ($start < 1) $start = 1;
        
        ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                const displayingNum = document.querySelector('.displaying-num');
                if (displayingNum) {
                    displayingNum.textContent = 'Showing <?php echo $start; ?> to <?php echo $end; ?> of <?php echo number_format_i18n($total_items); ?> items';
                }
            });
        </script>
        <?php
    }
}

实现方案二:用gettext钩子在PHP层面过滤文本

如果偏好后端处理,可通过过滤翻译文本实现,结合当前屏幕判断精准生效:

add_filter('gettext', 'custom_cpt_pagination_text', 10, 3);
function custom_cpt_pagination_text($translated_text, $text, $domain) {
    $target_cpt = 'your_cpt_slug';
    $current_screen = get_current_screen();
    
    // 仅在目标CPT列表页、匹配目标文本时生效
    if (isset($current_screen->id) && $current_screen->id === "edit-{$target_cpt}" && $domain === 'default') {
        if ($text === '%s item' || $text === '%s items') {
            global $wp_query;
            $page = get_query_var('paged') ?: 1;
            $ppp = get_query_var('posts_per_page');
            $total_items = $wp_query->found_posts;
            $end = min($ppp * $page, $total_items);
            $start = $end - $ppp + 1;
            if ($start < 1) $start = 1;
            
            $translated_text = sprintf('Showing %d to %d of %s', $start, $end, number_format_i18n($total_items)) . ' ' . $translated_text;
        }
    }
    return $translated_text;
}

使用说明

  1. 将代码添加到主题的functions.php文件或自定义插件中
  2. 替换代码中的your_cpt_slug为你的自定义文章类型实际slug
  3. 刷新自定义文章类型列表页即可看到效果

内容的提问来源于stack exchange,提问作者James Black

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 02:19:53