How to make method from plugin available in theme?

The question:

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:(

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.

Method 2

If your aren’t very familiar with PHP, use simple actions and filters in your theme, and register callbacks for those in your plugin class.

A basic example

Plugin

class Plugin_Class
{
    public function __construct()
    {
        $this->register_callbacks();
    }

    protected function register_callbacks()
    {
        add_filter( 'theme_foo', array( $this, 'foo' ) );
        add_action( 'theme_bar', array( $this, 'bar' ) );
    }

    public function foo()
    {
        return 'foo';
    }

    public function bar()
    {
        print 'bar';
    }
}

Theme

$foo = apply_filters( 'theme_foo', FALSE );

if ( $foo )
    echo "foo is $foo";

do_action( 'theme_bar' ); // prints 'bar'

Method 3

You have made a mistake in your functions. pluginslug_bar function doesn’t contain $foo variable, you need to initialize it first:

function pluginslug_get_foo() {
    $foo = new pluginslug_foo();
    return $foo;
}

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

Then in your theme’s functions.php file you can call it like this:

if ( function_exists( 'pluginslug_bar' ) ) {
    pluginslug_bar();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment