Skip to content

Instantly share code, notes, and snippets.

@schlessera schlessera/README.md
Created Mar 10, 2016

Embed
What would you like to do?
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>';
}
@schlessera

This comment has been minimized.

Copy link
Owner Author

schlessera commented Mar 10, 2016

screenshot 2016-03-10 11 43 14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.