无法在wordpress中访问函数外的变量
Cant access variable outside of function in wordpress
我无法理解为什么当 $theme_text_domain
放在 wordpress 中的以下函数之外时我无法访问它。
<?php
$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' );
我收到以下错误
Warning: Undefined variable $theme_text_domain in D:\Development\Php\wordpress\wp-content\themes\custom-components\functions.php on line 33
Warning: Undefined variable $theme_text_domain in D:\Development\Php\wordpress\wp-content\themes\custom-components\functions.php on line 34
但如果我将它放在函数中,它就可以正常工作。但我真的很想为 functions.php 文件中的所有函数声明一次文本域,而不是每次都输入文本域。这可能是一个愚蠢的问题,但为什么会这样。我假设因为它不在函数范围内,但显然不在范围内。
因为你正在使用一个动作。
Actions are the hooks that the WordPress core launches at specific
points during execution.
你可以做的是将其包装成 class。
我无法理解为什么当 $theme_text_domain
放在 wordpress 中的以下函数之外时我无法访问它。
<?php
$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' );
我收到以下错误
Warning: Undefined variable $theme_text_domain in D:\Development\Php\wordpress\wp-content\themes\custom-components\functions.php on line 33
Warning: Undefined variable $theme_text_domain in D:\Development\Php\wordpress\wp-content\themes\custom-components\functions.php on line 34
但如果我将它放在函数中,它就可以正常工作。但我真的很想为 functions.php 文件中的所有函数声明一次文本域,而不是每次都输入文本域。这可能是一个愚蠢的问题,但为什么会这样。我假设因为它不在函数范围内,但显然不在范围内。
因为你正在使用一个动作。
Actions are the hooks that the WordPress core launches at specific points during execution.
你可以做的是将其包装成 class。