Using OOP plugin’s methods throughout the website

I’m not entirely sure what you want to do exactly. But basically you just create one instance and then add functions like public static function FunctionName() to be used anywhere you want after the plugin got activated. To fire your hooks simply use the public function __construct().

Taking the Sample Plugin from below, the FooBar method can be called in any template like that:

<div class="foobar">
  <?php echo MyPlugin::FooBar(); ?>
</div>

And to call FooBar inside its class in another function you’d do:

self::FooBar();

Sample Plugin

<?php
/*
Plugin Name: My Plugin
Description: Lorem ipsum dolor sit amet.
Version: 1.0
Author: You
Author URI: https://example.com
*/

class MyPlugin {

  // Fire your hooks from here.
  public function __construct() {

    add_action('wp_enqueue_scripts', [$this, 'scripts']);
  }

  // Use any generic function to be used for hooks.
  function scripts() {

    wp_enqueue_script('abc_snippets', plugin_dir_url(__FILE__) . 'js/scripts.js', ['jquery'], NULL, TRUE);
  }

  // Use static public functions to also be used outside of this class.
  public static function FooBar() {

    return 'Hello World';
  }

}

new MyPlugin();

Leave a Comment