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

PHP 8升级后WordPress自定义分类法替换代码报错求助

解决PHP 8下WordPress分类法替换代码的致命错误

错误原因

PHP 8对未定义常量的解析逻辑做了严格升级:此前PHP遇到不带引号的函数名(如comma_taxonomy_filter)会先尝试解析为常量,找不到则退化为字符串;但PHP 8直接抛出未定义常量的致命错误——因为你传递的不是字符串形式的函数名,而是试图引用一个不存在的常量。

修复后的代码

只需给add_filter中所有函数名参数加上引号,以字符串形式传递即可解决问题:

if(!is_admin()){ // 仅在前端触发过滤器
    $custom_taxonomy_type = 'winners_name'; // 自定义分类法类型

    function comma_taxonomy_filter($tag_arr) {
        global $custom_taxonomy_type;
        $tag_arr_new = $tag_arr;
        if($tag_arr->taxonomy == $custom_taxonomy_type && strpos($tag_arr->name, '--')){
            $tag_arr_new->name = str_replace('--', ', ', $tag_arr->name);
        }
        return $tag_arr_new;    
    }
    // 函数名添加引号,以字符串形式传递
    add_filter('get_'.$custom_taxonomy_type, 'comma_taxonomy_filter');

    function comma_taxonomies_filter($tags_arr){
        $tags_arr_new = array();
        foreach($tags_arr as $tag_arr){
            $tags_arr_new[] = comma_taxonomy_filter($tag_arr);
        }
        return $tags_arr_new;
    }
    // 所有add_filter的函数名参数都添加引号
    add_filter('get_the_taxonomies',    'comma_taxonomies_filter');
    add_filter('get_terms',             'comma_taxonomies_filter');
    add_filter('get_the_terms',         'comma_taxonomies_filter');
}

可选优化方案

避免使用global变量,改用闭包传递参数,让代码更健壮且符合现代PHP编码规范:

if(!is_admin()){
    $custom_taxonomy_type = 'winners_name';

    $comma_taxonomy_filter = function($tag_arr) use ($custom_taxonomy_type) {
        $tag_arr_new = $tag_arr;
        if($tag_arr->taxonomy == $custom_taxonomy_type && strpos($tag_arr->name, '--')){
            $tag_arr_new->name = str_replace('--', ', ', $tag_arr->name);
        }
        return $tag_arr_new;    
    };
    add_filter('get_'.$custom_taxonomy_type, $comma_taxonomy_filter);

    $comma_taxonomies_filter = function($tags_arr) use ($comma_taxonomy_filter) {
        $tags_arr_new = array();
        foreach($tags_arr as $tag_arr){
            $tags_arr_new[] = $comma_taxonomy_filter($tag_arr);
        }
        return $tags_arr_new;
    };
    add_filter('get_the_taxonomies',    $comma_taxonomies_filter);
    add_filter('get_terms',             $comma_taxonomies_filter);
    add_filter('get_the_terms',         $comma_taxonomies_filter);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:12:35