Skip to content
Advertisement

Cant access variable outside of function in wordpress

I am having trouble understanding why I can’t access the $theme_text_domain when it is placed outside of the following function in 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' );

I am getting the following error

Warning: Undefined variable $theme_text_domain in D:DevelopmentPhpwordpresswp-contentthemescustom-componentsfunctions.php on line 33

Warning: Undefined variable $theme_text_domain in D:DevelopmentPhpwordpresswp-contentthemescustom-componentsfunctions.php on line 34

but if I place it inside the function it works fine. But I would really like to just state the text domain once for all of the functions inside of the functions.php file instead of typing out the text domain every time. This might be a silly question but why is this happening. I assume since it is outside of the function it is in scope but apparently not.

Advertisement

Answer

Because you are using an action.

Actions are the hooks that the WordPress core launches at specific points during execution.

What you can do is wrapping this into a class.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement