4
votes

I want to detect Yoast SEO. I already use this function:

function active( $plugin ) {
    $network_active = false;
    if ( is_multisite() ) {
        $plugins = get_site_option( 'active_sitewide_plugins' );
        if ( isset( $plugins[$plugin] ) ) {
            $network_active = true;
        }
    }
    return in_array( $plugin, get_option( 'active_plugins' ) ) || $network_active;
}

if ( active( 'wordpress-seo/wp-seo.php' ) {

And that works fine. But if Yoast ever thinks of renaming wordpress-seo/wp-seo.php, this function becomes useless. So we need to add an backup, something which is hard to change, like the WPSEO_VERSION constant:

if ( active( 'wordpress-seo/wp-seo.php' ) {
    // activate
} elseif( defined( 'WPSEO_VERSION' )) {
    // activate
} else {
    // deactivate
}

This line if( defined( 'WPSEO_VERSION' )) { for some reason does not detect Yoast.. how is that possible?

Thanks everyone.

4
First of all, we will not rename that file. Secondly, it is not save to check for any plugin related things without wrapping it on a plugins_loaded hook as Fencer04 pointed out. The hook plugins_loaded is triggered whenever all plugins are loaded, thus all constants and classes exist. Plugins are loaded in an order which can not be relied upon, it's not alphabetically. See codex.wordpress.org/Plugin_API/Action_Reference/plugins_loaded - Hope this helps, Jip from Yoast.moorscode
did you found the answer @hacked filesFatih Toprak

4 Answers

6
votes

This is as safe you can get:

if(in_array('wordpress-seo/wp-seo.php', apply_filters('active_plugins', get_option('active_plugins')))){ 
    /* Yoast is active */
}

And I would also suggest:

if(class_exists('WPSEO_Options')){
    /* Yoast is active */
    if(WPSEO_Options::get('breadcrumbs-enable', false)){
        /* Yoast breadcrumbs is active */
    }
}
5
votes

The simplest way is:

if ( is_plugin_active( 'wordpress-seo/wp-seo.php' ) || is_plugin_active( 'wordpress-seo-premium/wp-seo-premium.php' ) ) {
   /* Let's do cool things */
}

Function Reference/is plugin active

2
votes

Your function is probably checking WPSEO_VERSION before YOAST is loaded. Try using one of the following hooks to run the function that checks the WPSEO_VERSION constant.

add_action('init', 'active');

add_action('plugins_loaded', 'active');
1
votes

Well, Yoast adds <!-- / Yoast SEO plugin. --> in the source code, you can find it and if it's there, you got it. For example, here is a site that you can see it in it's source code.