問題描述
我正在構建一個插件,為主插件添加額外的功能。理想情況下,在插件管理屏幕中,”activate” 鏈接應該被禁用,並且應該添加一個內聯註釋,告訴用户在他/她可以使用當前插件之前首先安裝和激活主插件。
最佳解決方案
謝謝你們的答案。雖然這兩個答案都讓我走上了正確的道路,但沒有一個出來。所以我在下面分享我的解決方案。
方法 1 – 使用 register_activation_hook:
在插件/parent-plugin /parent-plugin.php 中創建父插件:
<?php
/*
Plugin Name: Parent Plugin
Description: Demo plugin with a dependent child plugin.
Version: 1.0.0
*/
在插件中創建子插件/child-plugin /child-plugin.php:
<?php
/*
Plugin Name: Child Plugin
Description: Parent Plugin should be installed and active to use this plugin.
Version: 1.0.0
*/
register_activation_hook( __FILE__, 'child_plugin_activate' );
function child_plugin_activate(){
// Require parent plugin
if ( ! is_plugin_active( 'parent-plugin/parent-plugin.php' ) and current_user_can( 'activate_plugins' ) ) {
// Stop activation redirect and show error
wp_die('Sorry, but this plugin requires the Parent Plugin to be installed and active. <br><a href="'%20.%20admin_url(%20'plugins.php'%20)%20.%20'">« Return to Plugins</a>');
}
}
請注意,由於某種原因,我不使用 deactivate_plugins( $plugin ); 它不起作用。所以我用 wp_die 取消激活重定向並通知用户。
優點:
-
簡單的解決方案,與方法 2 相比,不會產生額外的數據庫命中
缺點:
-
wp_die 屏幕是醜陋的
-
如果您使用插件管理屏幕中的複選框同時激活了父插件和子插件,wp_die 屏幕將顯示。
方法 2 – 使用 admin_init 和 admin_notices
在插件/parent-plugin /parent-plugin.php 中創建父插件:
<?php
/*
Plugin Name: Parent Plugin
Description: Demo plugin with a dependent child plugin.
Version: 1.0.0
*/
在插件中創建子插件/child-plugin /child-plugin.php:
<?php
/*
Plugin Name: Child Plugin
Description: Parent Plugin should be installed and active to use this plugin.
Version: 1.0.0
*/
add_action( 'admin_init', 'child_plugin_has_parent_plugin' );
function child_plugin_has_parent_plugin() {
if ( is_admin() && current_user_can( 'activate_plugins' ) && !is_plugin_active( 'parent-plugin/parent-plugin.php' ) ) {
add_action( 'admin_notices', 'child_plugin_notice' );
deactivate_plugins( plugin_basename( __FILE__ ) );
if ( isset( $_GET['activate'] ) ) {
unset( $_GET['activate'] );
}
}
}
function child_plugin_notice(){
?><div class="error"><p>Sorry, but Child Plugin requires the Parent plugin to be installed and active.</p></div><?php
}
優點:
-
當您同時使用複選框激活父和子插件時工作
壞處:
-
Incur 其他數據庫命中,首先實際激活插件,並在 admin_init 運行時停用。
至於我關於禁用激活鏈接的問題,我可以使用:
add_filter( 'plugin_action_links', 'disable_child_link', 10, 2 );
function disable_child_link( $links, $file ) {
if ( 'child-plugin/child-plugin.php' == $file and isset($links['activate']) )
$links['activate'] = '<span>Activate</span>';
return $links;
}
但是,由於沒有地方放這個代碼,原來是非常不切實際的。我不能把它放在父插件上,因為父插件應該是活動的,代碼可以運行。當然不屬於子插件或 functions.php 。所以我打破了這個想法。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。