Displaying a variable stored in functions.php inside widget

I’m trying to display a variable that is stored inside my functions.php file – for the sake of the question this variable is stored as $test = 'test';. When i use echo $test inside page.php, header.php or any other file the value is returned however when i try to do the same inside a widget (i’m using a plugin that allows execution of PHP inside a widget) nothing happens.

Any ideas as to how i could get around this?

Related posts

1 comment

  1. The widget operates in a different scope than the functions.php.

    You could use two different approaches to get around that.

    1. Make the variable global (put it into the top scope):

      // functions.php
      $GLOBALS['var_name'] = 'hello';
      
      // widget
      echo $GLOBALS['var_name'];
      

      But that is risky: any other script can change the variable now accidentally, and it is very hard to debug this.

    2. Create a special class or function for the variable. You could even use one class or function to store many values. Example:

      class Theme_Data
      {
          private $data = array();
      
          public function __construct( $filter = 'get_theme_data_object' )
          {
              add_filter( $filter, array ( $this, 'get_instance' ) );
          }
      
          public function set( $name, $value )
          {
              $this->data[ $name ] = $value;
          }
      
          public function get( $name )
          {
              if ( isset ( $this->data[ $name ] ) )
                  return $this->data[ $name ];
      
              return NULL;
          }
      
          public function get_instance()
          {
              return $this;
          }
      }
      

      In your functions.php, you can create an object now and add a value:

      $theme_data = new Theme_Data();
      $theme_data->set( 'default_posts_in_news_widget', 10 );
      

      In your widget, you can get that object and the stored value:

      // widget
      $theme_data = apply_filters( 'get_theme_data_object', NULL );
      
      if ( is_a( $theme_data, 'Theme_Data' ) )
          $num = $theme_data->get( 'default_posts_in_news_widget' );
      else
          $num = 5;
      

      You can even create multiple independent Theme_Data objects for different purposes, just create them with different $filter strings:

      $widget_data     = new Theme_Data( get_template() . '_widgets' );
      $customizer_data = new Theme_Data( get_template() . '_customizer' );
      

Comments are closed.