开发者

How Do I Programmatically Check if a WordPress Plugin Is Already Activated?

开发者 https://www.devze.com 2022-12-27 05:53 出处:网络
I know I can use activate_plugin() from inside a given, active plugin in WordPress, to activate another plugin. But what I want to know is how do I programmatically check if that plugin is already act

I know I can use activate_plugin() from inside a given, active plugin in WordPress, to activate another plugin. But what I want to know is how do I programmatically check if that plugin is already active?

For instance, this snippet of code can be temporarily added to an existing plugin's initial file to activate a partner plugin:

add_action('wp','activatePlugins');

function activatePlugins() {
  if( is_single() || is_page() || is_home() 开发者_运维知识库|| is_archive() || is_category() || is_tag()) {
    @ activate_plugin('../mypartnerplugin/thepluginsmainfile.php');
  }
}

Then, use a Linux command line tool to spider all your sites that have this code, and it will force a page view. That page view will cause the above code to fire and activate that other plugin. That's how to programmatically activate another plugin from a given plugin as far as I can tell.

But the problem is that it gets activated over and over and over again. What would be great is if I had an if/then condition and some function I could call in WordPress to see if that plugin is already activated, and only activate it once if not active.


Here's the solution:

http://codex.wordpress.org/Function_Reference/is_plugin_active

<?php
   if (!is_plugin_active('plugin-directory-path/plugin-file.php')) {
      @ activate_plugin('plugin-directory-path/plugin-file.php');
   }

You can set that plugin-directory-path either to a fixed path, or to a relative path. (Just not a web URL path.)

Note that wp-admin/includes/plugin.php must be loaded for the above code to work. Therefore, the final solution was:

add_action('wp','myPluginTool');

function myPluginTool() {
if( is_single() || is_page() || is_home() || is_archive() || is_category() || is_tag()) {

  $sDir = dirname(__FILE__);
  $sDir = rtrim($sDir, '/');
  $sDir = str_replace('/myplugin','',$sDir); // myplugin was folder name of current plugin
  $sDir = rtrim($sDir, '/');

  require_once($sDir . '/../../wp-admin/includes/plugin.php');

  // DEACTIVATE
  if (is_plugin_active($sDir . '/partnerplugin/partner.php')) {
    deactivate_plugins($sDir . '/partnerplugin/partner.php');
  }

  /*
  // ACTIVATE
  if (!is_plugin_active($sDir . '/partnerplugin/partner.php')) {
    activate_plugin($sDir . '/partnerplugin/partner.php');
  }
  */
}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消