Including file or library from other plugin

I’m creating a plugin I would like to use from other different plugins. This plugin declares classes and functions. So, I am thinking about the best way to include, from one plugin, a php file present in another plugin.

I think this should work:

Read More
require_once WP_PLUGIN_DIR . "/the-other-plugin/required-file.php";

But I am not sure; is it a good solution? I think this would work even if the-other-plugin is not enabled, and probably that is not a good idea.

This can be done also by using Must Use Plugins. Is this a best practice, or is the other solution better?

Related posts

Leave a Reply

1 comment

  1. In your plugin add a custom action to let other plugins start after your basic code has done the work:

    // load basic classes
    do_action( 'my_library_loaded', plugin_dir_path( __FILE__ ) );
    

    Other plugins can start their work now like this:

    add_action( 'my_library_loaded', 'other_plugin_init_handler' );
    

    They will never do anything if your base plugin is not active.

    The other plugin’s start function gets the correct path now as parameter:

    function other_plugin_init_handler( $base_path )
    {
        require_once $base_path . 'classes/Template_Handler.php' );
    
        $template = new Template_Handler;
    }
    

    You could also offer a custom class load function in the base plugin. The basic idea here is: Do not let other plugins guess a path.