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

WordPress主题开发报错:Cannot redeclare add_theme_support()

解决Cannot redeclare add_theme_support()致命错误

原代码与报错

用户主题的functions.php代码如下:

<?php
if (function_exists('add_theme_support')) {
    add_theme_support('post-thumbnails');
}
function add_theme_support() {
    wp_enqueue_style('bootstrap', get_template_directory_uri().'/bootstrap/css/bootstrap.rtl.min.css');
    wp_enqueue_style('bootstrap', get_template_directory_uri().'/style.css');
    wp_enqueue_script('bootstrap', get_template_directory_uri().'/bootstrap/js/bootstrap.min.js');
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');

运行后触发致命错误:

Fatal error: Cannot redeclare add_theme_support() (previously declared in C:\xampp\htdocs\projects\cms\wordpress\wp-includes\theme.php:2576) in C:\xampp\htdocs\projects\cms\wordpress\wp-content\themes\oxbir\functions.php on line 5

错误原因

  1. 函数重名冲突:add_theme_support是WordPress核心内置函数,主题代码中重新定义同名函数,违反PHP函数不可重复声明的规则。
  2. 钩子回调不匹配:add_action指定的回调函数是add_theme_scripts,但实际定义的函数是add_theme_support,导致资源加载逻辑无法执行。
  3. 资源Handle重复:注册CSS和JS时均使用bootstrap作为handle,后注册的资源会覆盖前者,导致Bootstrap CSS被主题样式覆盖。

修复后的代码

<?php
// 直接启用文章缩略图功能(核心函数无需额外判断存在性)
add_theme_support('post-thumbnails');

// 自定义资源加载函数,用主题名前缀避免冲突
function oxbir_enqueue_theme_assets() {
    // 加载Bootstrap CSS,使用唯一handle
    wp_enqueue_style('oxbir-bootstrap-css', get_template_directory_uri() . '/bootstrap/css/bootstrap.rtl.min.css');
    
    // 加载主题样式,设置依赖Bootstrap CSS保证加载顺序
    wp_enqueue_style('oxbir-theme-style', get_template_directory_uri() . '/style.css', array('oxbir-bootstrap-css'));
    
    // 加载Bootstrap JS,依赖WordPress内置jQuery,设置在页脚加载提升性能
    wp_enqueue_script('oxbir-bootstrap-js', get_template_directory_uri() . '/bootstrap/js/bootstrap.min.js', array('jquery'), '', true);
}
// 绑定回调到wp_enqueue_scripts钩子
add_action('wp_enqueue_scripts', 'oxbir_enqueue_theme_assets');

关键注意点

  • 自定义函数添加主题名前缀(如oxbir_),彻底避免与核心/其他插件函数重名。
  • 每个资源使用唯一handle,确保所有资源正常加载不被覆盖。
  • 声明资源依赖关系,保证样式和脚本按正确顺序加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:36:18