Usually I use this method to test whether a plugin is active (usually my own).

This would be in the plugin I'm checking for:

function my_plugin_setup() {
    // setup code here
add_action( 'plugins_loaded', 'my_plugin_setup' );

From another file or plugin I would use has_filter on the function which is fired on plugins_loaded:

if ( has_filter( 'plugins_loaded', 'my_plugin_setup' ) ) {
    // plugin is active, do something

How would I use this same method above but for a class based plugin? Ie the plugin code looks something like:

class My_Plugin {

    public function __construct() {
        add_action( 'plugins_loaded', array( $this, 'setup' ) );    

    // other stuff below

Obviously this doesn't work:

if ( has_filter( 'plugins_loaded', array( $this, 'My_Plugin' ) ) ) {
    // do something

Note: I'd like to use this method instead of using is_plugin_active because the plugin's folder name might change and hence is_plugin_active would no longer work.


To do literally what you're wanting here, the easiest way is to store the instance of the plugin class in a global variable at the end of your plugin:

class My_Plugin {
    static $instance;
    function __construct(){} /* or private, with singleton get_instance() method */
    function setup(){ ... }
$my_plugin_instance = new My_Plugin();
add_action( 'plugins_loaded', array( $my_plugin_instance, 'setup' ) );

Then you can do:

$has_plugin = (
    isset( $my_plugin_instance ) 
    has_filter( 'plugins_loaded', array( $my_plugin_instance, 'setup' )
if ( $has_plugin ) ...

However, this approach to see if a plugin has been loaded seems overly complicated. Why not just check to see if class_exists( 'My_Plugin' )? If the class does exist, then you know the plugin was loaded. No need to do any checks for if a filter was added.

  • I'm not sure where I read it, but it was advised to check for the presence of filters, rather than use class_exists. I used your example above, but when the plugin is deactivated, it throws a fatal error that the class was not found. Maybe I'll just stick to using class_exists until I understand it a bit more. – Andrew Jul 6 '13 at 1:43
  • 1
    Yes, right. Using a static member variable would blow up when the plugin is deactivated. In that case, you could store it in a global variable $my_plugin. But yeah, I see no reason why using class_exists would be inadequate. – Weston Ruter Jul 6 '13 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.