How to make method from plugin available in theme?

Let’s say this was in my plugin:

class pluginslug_foo {
    public function bar() {
         //stuff
    }
}

and I wanted to make the method bar available for use outside of the plugin, for instance in a theme file so it could be called with pluginslug_bar();.

I tried:

function pluginslug_get_foo() {
      $foo = new pluginslug_foo();
      return $foo;
}
function pluginslug_bar() {
      $bar = $foo->bar;
}

But I got an unknown variable error for $bar when I tried pluginslug_bar(); in my theme:(

3 s
3

An alternative way is to use static class methods in plugins, and optionally write functions as alias:

in Plugin:

class Pluginslug_Foo {

    static $foo = 'Bar!';

    public static function bar() {
       return self::$foo;
    }

}

if ( ! function_exists( 'pluginslug_bar' ) ) {
    function pluginslug_bar() {
       echo Pluginslug_Foo::bar();
    }
}

in Theme:

if ( function_exists( 'pluginslug_bar' ) ) {
    pluginslug_bar(); // echo 'Bar!';
}

or

if ( method_exists('Pluginslug_Foo', 'bar' ) ) {
     echo Pluginslug_Foo::bar(); // echo 'Bar!';
}

Of course static methods and variables not always fit the scope, and this is a general theoric example: without know your real scope/code is impossible to say if it’s good for you or not.

Leave a Comment