Skip to content

Instantly share code, notes, and snippets.

@schlessera
Created March 10, 2016 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save schlessera/0e6e71a9f909d5608b00 to your computer and use it in GitHub Desktop.
Save schlessera/0e6e71a9f909d5608b00 to your computer and use it in GitHub Desktop.
Accessing WP plugin code from a theme
<?php
/**
* Example plugin.
*
* @see http://wordpress.stackexchange.com/questions/220286/what-is-the-best-way-to-instantiate-a-class-of-a-plugin-in-your-wordpress-theme/
*
* @wordpress-plugin
* Plugin Name: Example plugin.
* Description: Accessing a plugin object from a theme.
* Version: 0.1.0
* Author: Alain Schlesser
* Author URI: https://www.alainschlesser.com/
* Text Domain: example-plugin
* Domain Path: /languages
* License: GPL-2.0+
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
// Load Composer autoloader.
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
require_once __DIR__ . '/vendor/autoload.php';
}
/**
* Class ExamplePlugin.
*
* This is only a demonstration of how to access a plugin from
* within a theme using an instance getter.
*
* @author Alain Schlesser <alain.schlesser@gmail.com>
*/
class ExamplePlugin {
/**
* Static instance of the plugin.
*
* @var ExamplePlugin
*/
protected static $instance;
/**
* Get a reference to the Plugin instance.
*/
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Launch the initialization process.
*/
public function run() {
// Do your normal plugin stuff here.
}
/**
* Return a string to demonstrate that the plugin works.
*/
public function hello_world() {
return 'Hello World (from a plugin)!';
}
}
/**
* This is our function to retrieve an instance to the plugin
* from the theme.
*
* @return ExamplePlugin
*/
function example_plugin_get_instance() {
return ExamplePlugin::get_instance();
}
// Launch the plugin so that it can do its normal job.
ExamplePlugin::get_instance()->run();
<?php
add_filter( 'the_content', 'example_content_filter_static_method' );
/**
* Fetch the plugin instance through a static method of the plugin.
*/
function example_content_filter_static_method( $content ) {
$example_plugin = ExamplePlugin::get_instance();
return $content . '<p style="color: green;">' . $example_plugin->hello_world() . '</p>';
}
add_filter( 'the_content', 'example_content_filter_function' );
/**
* Fetch the plugin instance through a function of the plugin.
*/
function example_content_filter_function( $content ) {
$example_plugin = example_plugin_get_instance();
return $content . '<p style="color: red;">' . $example_plugin->hello_world() . '</p>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment