플러그인을 만드는 방법에는 다른 플러그인이 필요합니까?


30

기본 플러그인에 추가 기능을 추가하는 플러그인을 작성 중입니다. 이상적으로는 플러그인 관리 화면에서 "활성화"링크를 비활성화하고 인라인 노트를 추가하여 사용자가 현재 플러그인을 사용하기 전에 기본 플러그인을 먼저 설치하고 활성화하도록 지시해야합니다.


1
is_plugin_active () 사용은 어떻습니까? 예 : if (is_plugin_active('path/to/plugin.php')) { // Do something }
TomC

답변:


35

답변 주셔서 감사합니다. 두 가지 대답 모두 나를 올바른 길로 안내했지만 상자 밖으로 나가는 사람은 없었습니다. 그래서 나는 내 솔루션을 아래에서 공유하고 있습니다.

방법 1-register_activation_hook 사용 :

plugins / parent-plugin / parent-plugin.php에 Parent Plugin을 생성하십시오 :

<?php
/*
Plugin Name: Parent Plugin
Description: Demo plugin with a dependent child plugin.
Version: 1.0.0
*/

plugins / 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="' . admin_url( 'plugins.php' ) . '">&laquo; Return to Plugins</a>');
    }
}

내가 사용하지 않는 것을주의 deactivate_plugins( $plugin );가 작동하지 않는 몇 가지 이유가있다. 그래서 wp_die를 사용하여 활성화 리디렉션을 취소하고 사용자에게 알립니다.

이점:

  • 간단한 솔루션이며 방법 2에 비해 추가 DB 적중이 발생하지 않습니다.

단점 :

  • wp_die 화면이보기 흉하다
  • 플러그인 관리 화면의 확인란을 사용하여 부모 플러그인과 자식 플러그인을 동시에 활성화하면 wp_die 화면이 여전히 나타납니다.

방법 2-admin_init 및 admin_notices 사용

plugins / parent-plugin / parent-plugin.php에 Parent Plugin을 생성하십시오 :

<?php
/*
Plugin Name: Parent Plugin
Description: Demo plugin with a dependent child plugin.
Version: 1.0.0
*/

plugins / 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
}

이점:

  • 확인란을 사용하여 부모 및 자식 플러그인을 동시에 활성화 할 때 작동

불리:

  • 플러그인이 실제로 처음 활성화되고 admin_init가 실행되면 비활성화 될 때 추가 DB 적중이 발생합니다.

활성화 링크 비활성화에 관한 내 질문에 대해서는 다음을 사용할 수 있습니다.

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에 속하지 않습니다. 그래서 저는이 아이디어를 폐기하고 있습니다.


1
방법 2는 훌륭하게 작동했습니다! 다른 사람의 플러그인을 확장하는 데 사용했습니다.
Collin Price

2

주석 처리되어 있으므로 이해하는 데 도움이됩니다.

<?php
register_activation_hook( __FILE__, 'myplugin_activate' ); // Register myplugin_activate on
function myplugin_activate() {
    $plugin = plugin_basename( __FILE__ ); // 'myplugin'
    if ( is_plugin_active( 'plugin-directory/first-plugin.php' ) ) {
        // Plugin was active, do hook for 'myplugin'
    } else {
        // Plugin was not-active, uh oh, do not allow this plugin to activate
        deactivate_plugins( $plugin ); // Deactivate 'myplugin'
    }
}
?> 

오류가 발생하면 'myplugin'의 '옵션'을 확인하여 false로 설정하거나 활성화하지 않을 수도 있습니다.


2

제안 된 솔루션 모두 결함이 있습니다.

방법 1 : 언급 한 바와 같이 플러그인 관리 화면의 확인란을 사용하여 부모 플러그인과 자식 플러그인이 동시에 활성화되면 wp_die () 화면이 여전히 나타납니다.

방법 2 : 일부 유스 케이스의 경우 'admin_init'가 'plugins_loaded'( https://codex.wordpress.org/Plugin_API/Action_Reference ) 이후 및 제거 후크 ( https : // codex ) 후에 실행되므로 좋지 않습니다 . wordpress.org/Function_Reference/register_uninstall_hook ). 예를 들어 부모 플러그인의 활성화 여부에 관계없이 애드온이 제거시 일부 코드를 실행하도록하려면이 방법이 작동하지 않습니다.

해결책:

우선 부모 플러그인의 메인 PHP 파일 끝에 다음 코드를 추가해야합니다.

do_action( 'my_plugin_loaded' );

그러면 모든 가입자에게 이벤트 / 신호를 전달하여 핵심 플러그인이로드되었음을 알립니다.

그런 다음 추가 기능 클래스는 다음과 같아야합니다.

class My_Addon
{
    static function init ()
    {
        register_activation_hook( __FILE__, array( __CLASS__, '_install' ) );

        if ( ! self::_is_parent_active_and_loaded() ) {
            return;
        }
    }

    #region Parent Plugin Check

    /**
     * Check if parent plugin is activated (not necessarly loaded).
     *
     * @author Vova Feldman (@svovaf)
     *
     * @return bool
     */
    static function _is_parent_activated()
    {
        $active_plugins_basenames = get_option( 'active_plugins' );
        foreach ( $active_plugins_basenames as $plugin_basename ) {
            if ( false !== strpos( $plugin_basename, '/my-plugin-main-file.php' ) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if parent plugin is active and loaded.
     *
     * @author Vova Feldman (@svovaf)
     *
     * @return bool
     */
    static function _is_parent_active_and_loaded()
    {
        return class_exists( 'My_Plugin' );
    }

    /**
     *
     * @author Vova Feldman (@svovaf)
     */
    static function _install()
    {
        if ( ! self::_is_parent_active_and_loaded() ) {
            deactivate_plugins( basename( __FILE__ ) );

            // Message error + allow back link.
            wp_die( __( 'My Add-on requires My Plugin to be installed and activated.' ), __( 'Error' ), array( 'back_link' => true ) );
        }
    }

    #endregion Parent Plugin Check
}

if (My_Addon::_is_parent_active_and_loaded())
{
    // If parent plugin already included, init add-on.
    My_Addon::init();
}
else if (My_Addon::_is_parent_activated())
{
    // Init add-on only after the parent plugins is loaded.
    add_action( 'my_plugin_loaded', array( __CLASS__, 'init' ) );
}
else
{
    // Even though the parent plugin is not activated, execute add-on for activation / uninstall hooks.
    My_Addon::init();
}

그것이 도움이되기를 바랍니다 :)


4
이 답변에도 결함이 있습니다. :-) do_action ( 'my_plugin_loaded')을 추가 할 수있는 상위 플러그인을 완전히 제어한다고 가정합니다. 코드에서. 선택한 답변은 부모 플러그인의 제어 여부와 관계없이 작동합니다 (예 : 부모 플러그인은 귀하의 것이 아닙니다)
kosinix

고마워요, 이것은 내가 찾던 것입니다. 내 경우에는, 내가 부모 플러그인을 완벽하게 제어 할 수 있고, 의존성의이 종류를 만드는 데 필요한.
cr0ybot

0

TGM 플러그인 활성화 가 필요하다고 생각합니다 .

TGM 플러그인 활성화 는 WordPress 테마 (및 플러그인) 용 플러그인을 쉽게 요구하거나 추천 할 수있는 PHP 라이브러리입니다. 기본 WordPress 클래스, 함수 및 인터페이스를 사용하여 단일 또는 대량 방식으로 플러그인을 설치, 업데이트 및 자동으로 활성화 할 수 있습니다. 번들 플러그인, WordPress 플러그인 리포지토리의 플러그인 또는 인터넷의 다른 곳에서 호스팅되는 플러그인을 참조 할 수 있습니다.


링크가 잘못되었습니다. 여기에
XedinUnknown
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.