【问题标题】:Cant access variable outside of function in wordpress无法在wordpress中访问函数之外的变量
【发布时间】:2021-11-11 17:36:06
【问题描述】:

当 $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 文件中的所有函数声明一次文本域,而不是每次都输入文本域。这可能是一个愚蠢的问题,但为什么会这样。我假设因为它在函数之外,所以它在范围内,但显然不在。

【问题讨论】:

标签: php wordpress scope


【解决方案1】:

因为你正在使用一个动作。

Actions 是 WordPress 核心在特定位置启动的钩子 执行期间的点数。

你可以做的就是把它包装到一个类中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2022-06-13
    • 2021-01-15
    • 2021-12-24
    • 1970-01-01
    • 2014-04-09
    相关资源
    最近更新 更多