1

I am adding theme options to Wordpress and I have a Theme_Options class for this.

Inside the class I have get_field($field) method to grab the theme option.

I would like to create a function so I can use in the WordPress Theme that I am building to grab the theme option, but I do not want to use global variable.

class Theme_options
{
    public function __construct()
    {
    }

    public function get_field($field) 
    {
        // logic to get the theme option
        return $field;
    }
}

Right now I need to use global $Theme_Options to create get_field() function.

$Theme_Options = new Theme_Options();


function get_field($field) {
    global $Theme_Options
    return $Theme_Options->get_field($field);
}

How can I create get_field() function without using global variable inside that function?

yivi
  • 23,845
  • 12
  • 64
  • 89

1 Answers1

1

The whole design is rather weird, but considering the limitations you are working with, something like a singleton could work.

class ThemeOptions
{

    private static $instance;

    private function __construct()
    {
    }

    public static function getInstance() {

        if (self::$instance === null) {
            self:$instance = new self();
        }

        return self::$instance;
    }

    public function getField($field) 
    {
        // logic to get the theme option
        return $field;
    }
}

$ThemeOptions = ThemeOptions::getInstance();

// do whatever initialization you want to $ThemeOptions;


function get_field($field) {
    return ThemeOptions::getInstance()->getField($field);
}

A Singleton is not a great design pattern, but I know developing for WP you are more constrained than usual. The singleton instance lives in the global space, since it's stored in a static property.

You can't initialize the class more than once, since the private constructor forces to go through getInstance(), making sure there is no more than one Theme_Options instance at any time.

You'd initialize the ThemeOptions object during plugin initialization, and you could use the get_field() function in your templates. Since template rendering comes after plugin initialization, by then your ThemeOptions instance would have been appropriately populated.

yivi
  • 23,845
  • 12
  • 64
  • 89