检测 Yoast SEO 插件

Hac*_*les 5 wordpress plugins

我想检测 Yoast SEO。我已经使用了这个功能:

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' ) {
Run Code Online (Sandbox Code Playgroud)

效果很好。但如果 Yoast 想到重命名wordpress-seo/wp-seo.php,这个功能就变得毫无用处。所以我们需要添加一个备份,一些很难改变的东西,比如常量WPSEO_VERSION

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

由于某种原因,这条线if( defined( 'WPSEO_VERSION' )) {没有检测到 Yoast.. 这怎么可能?

感谢大家。

Ivi*_*pić 8

最简单的方法是:

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

功能参考/插件是否处于活动状态


Jon*_*man 6

这是您可以获得的最安全的:

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

我还建议:

if(class_exists('WPSEO_Options')){
    /* Yoast is active */
    if(WPSEO_Options::get('breadcrumbs-enable', false)){
        /* Yoast breadcrumbs is active */
    }
}
Run Code Online (Sandbox Code Playgroud)


Fen*_*r04 2

您的函数可能在加载 YOAST 之前检查 WPSEO_VERSION。尝试使用以下挂钩之一来运行检查 WPSEO_VERSION 常量的函数。

add_action('init', 'active');

add_action('plugins_loaded', 'active');
Run Code Online (Sandbox Code Playgroud)