I'm developing a plugin for a site that has to communicate with several non-wp tables in a database. For that I made a class that contains all of the MySQL-related functions.

When you declare a function within a plugin, you can easily call it within a theme. But how to do that with a class? Is there a way to instantiate it with wordpress init and make it available to plugin(s) and theme(s)?

Thank you for your time! :)


Ryan McCue had a nice idea for his plugin Hopper: add a callback for a custom filter to return the current instance.

Sample code for the plugin:

class Plugin_Class {
    public function __construct()
        add_filter( 'get_plugin_class', array ( $this, 'provide_instance' ) );

    function provide_instance() {
        return $this;

In a theme or a second plugin you can access the instance now like this:

$plugin_class = apply_filters( 'get_plugin_class', NULL );

if ( is_a( $plugin_class, 'Plugin_Class' ) )
    // use the plugin class instance
| improve this answer | |
  • Wow, this solution is amazing. I would've never thought of that! I really love the fact it instantiates the class only once. :) Thank you!!! :) – Vorta Dec 19 '13 at 15:14

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.