How do I use the Simple HTML DOM Parser in plugin when other plugin already uses it?

In a plugin I am currently coding, I want to use the Simple HTML DOM Parser library. However, when I include it

require(CPS_PLUGIN_PATH . '/vendor/simple_html_dom.php');

I get this error:

Fatal error: Cannot redeclare file_get_html() (previously declared in /www/htdocs/12345/mydomain.com/wp-content/plugins/custom-post-snippets/vendor/simple_html_dom.php:48) in /www/htdocs/12345/mydomain.com/wp-content/plugins/fast-velocity-minify/libs/simplehtmldom/simple_html_dom.php on line 54

So obviously the Fast Velocity Minify plugin is already using it. What do I do here, if I don't want to mess around in the library itself? What's the best practice in a case like this?

Topic include php library plugin-development Wordpress

Category Web


If you don't want to mess with plugin load order, you can trigger the require part a bit later, e.g. via the plugins_loaded hook.

function csp_require_simplehtml() {
    if (!function_exists('file_get_html')) {
        require(CPS_PLUGIN_PATH . '/vendor/simple_html_dom.php');
    }
}
add_action('plugins_loaded', 'csp_require_simplehtml');

As @Sally CJ pointed out I had to use function_exists('file_get_html'), like so:

if (!function_exists('file_get_html')) {
    require(CPS_PLUGIN_PATH . '/vendor/simple_html_dom.php');
}

However, that did still not do the trick at first, since the error was not occuring in my plugin but in the Fast Velocity Minify plugin, that was loaded first. So I had to change the order in which the plugins where loaded. I put my plugin at the very end of the loading sequence, with this code:

function csp_load_last()
{
    $path = str_replace( WP_PLUGIN_DIR . '/', '', __FILE__ );
    if ( $plugins = get_option( 'active_plugins' ) ) {
        if ( $key = array_search( $path, $plugins ) ) {
            array_splice( $plugins, $key, 1 );
            array_push( $plugins, $path );
            update_option( 'active_plugins', $plugins );
        }
    }
}

add_action( 'activated_plugin', 'csp_load_last' );

The code has to go into the main plugin file, which in my case is the custom-post-snippets.php.

I only hope this doesn't cause any other errors, but until now it seems to be working fine like this.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.