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

WordPress中如何引入并激活独立文件内的自定义功能代码?

实现方法

你只需要在functions.php中引入两个存放业务代码的文件即可,无需把所有代码都塞到functions.php里。


代码实现

如果你的posttypes.php和taxonomy.php中已经写好了对应注册函数、且已经绑定了init钩子,只需要加2行引入代码:

require_once get_template_directory() . '/custom/posttypes.php';
require_once get_template_directory() . '/custom/taxonomy.php';

如果两个文件里只写了注册函数、没有绑定钩子,再加2行绑定代码即可:

// 引入自定义文章类型、分类法代码
require_once get_template_directory() . '/custom/posttypes.php';
require_once get_template_directory() . '/custom/taxonomy.php';

// 绑定注册动作到WordPress初始化钩子
add_action( 'init', 'cptui_register_my_cpts_testimonials' );
add_action( 'init', 'cptui_register_my_taxes_client-types' );

注意事项

  • 必须用get_template_directory()获取主题根目录的绝对路径,不要使用相对路径,避免不同环境下路径解析出错
  • 不要把自定义文章类型、分类法的注册动作绑定到主题激活钩子,必须绑定到init钩子,否则会出现路由不生效、访问404的问题
  • 如果要避免主题激活后首次访问自定义文章类型出现404,可以额外加一段固定链接刷新代码:
add_action( 'after_switch_theme', function() {
    flush_rewrite_rules();
} );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 15:51:03