WordPress自定义函数无法访问外部$theme_text_domain变量问题咨询
问题产生原因
这是PHP的作用域规则导致的,函数内部默认拥有独立的作用域,无法直接访问外部定义的全局变量,和WordPress本身逻辑无关。你之前的认知误区在于误以为同文件内的全局变量可以直接在函数内读取,实际上PHP的全局变量必须显式声明后才能在函数内部使用。
解决方案
推荐优先级从高到低如下:
方案1:使用全局常量定义(最推荐,符合WordPress主题开发规范)
文本域属于固定不变的配置值,用常量定义可以全局生效无需额外声明,也不会被意外修改:
<?php // 全局定义文本域常量,所有函数、文件都可直接访问 define('THEME_TEXT_DOMAIN', 'theme-text-domain'); function theme_widgets() { register_sidebar( array( 'id' => 'primary', 'name' => __( 'Primary Sidebar', THEME_TEXT_DOMAIN ), 'description' => __( 'Primary Sidebar', THEME_TEXT_DOMAIN ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'theme_widgets' );
方案2:函数内部显式声明global变量
如果你坚持使用变量存储,可以在每个需要调用该变量的函数内部用global关键字引入全局变量:
<?php $theme_text_domain = 'theme-text-domain'; function theme_widgets() { // 显式声明要使用的全局变量 global $theme_text_domain; register_sidebar( array( 'id' => 'primary', 'name' => __( 'Primary Sidebar', $theme_text_domain ), 'description' => __( 'Primary Sidebar', $theme_text_domain ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'theme_widgets' );
该方案的缺点是每一个用到该变量的函数都需要单独加global声明,漏写就会报错,且变量可被任意位置修改,稳定性不如常量。
方案3:闭包传值
如果是用匿名函数注册钩子,可以通过use关键字传入外层变量:
<?php $theme_text_domain = 'theme-text-domain'; add_action('widgets_init', function() use ($theme_text_domain) { register_sidebar( array( 'id' => 'primary', 'name' => __( 'Primary Sidebar', $theme_text_domain ), 'description' => __( 'Primary Sidebar', $theme_text_domain ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); });
该方案仅适合单次使用的场景,多函数调用时重复代码较多。
内容的提问来源于stack exchange,提问作者user3331344
相关产品推荐
相关产品推荐

