본문 바로가기

[wordpress] plugin Activation/Deactivation/Uninstall hook

web/wordpress by 코나인 2023. 5. 7.
반응형

워드프레스 플러그인 제작시 필수로 알아야할 활성화/비활성화/삭제 구현 방법입니다.

 

 

Activation

Activation 후크를 설정하려면 register_activation_hook() 함수를 사용합니다.

/**
 * Register the "book" custom post type
 */
function pluginprefix_setup_post_type() {
	register_post_type( 'book', ['public' => true ] ); 
} 
add_action( 'init', 'pluginprefix_setup_post_type' );


/**
 * Activate the plugin.
 */
function pluginprefix_activate() { 
	// Trigger our function that registers the custom post type plugin.
	pluginprefix_setup_post_type(); 
	// Clear the permalinks after the post type has been registered.
	flush_rewrite_rules(); 
}
register_activation_hook( __FILE__, 'pluginprefix_activate' );

 

Deactivation

Deactivation 후크를 설정하려면 register_deactivation_hook() 함수를 사용합니다.

/**
 * Deactivation hook.
 */
function pluginprefix_deactivate() {
	// Unregister the post type, so the rules are no longer in memory.
	unregister_post_type( 'book' );
	// Clear the permalinks to remove our post type's rules from the database.
	flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'pluginprefix_deactivate' );

 

Uninstall

Uninstall 두가지 방법이 있습니다. 하나는 uninstall hook를 설정하는 것이고 다른 하나는 uninstall.php 파일을 생성하는 것입니다.

 

방법 1.

register_uninstall_hook() 함수 사용하기

register_uninstall_hook(
	__FILE__,
	'pluginprefix_function_to_run'
);

 

방법2.

uninstall.php 사용하기

// if uninstall.php is not called by WordPress, die
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
    die;
}

$option_name = 'wporg_option';

delete_option( $option_name );

// for site options in Multisite
delete_site_option( $option_name );

// drop a custom database table
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}mytable" );

 

 

참조한 공식문서

 

1. Activation/Deactivation hook

 

WordPress Developer Resources | Official WordPress Developer Resources

Official WordPress developer resources including a code reference, handbooks (for APIs, plugin and theme development, block editor), and more.

developer.wordpress.org

 

 

2. Uninstall hook & uninstall.php

 

WordPress Developer Resources | Official WordPress Developer Resources

Official WordPress developer resources including a code reference, handbooks (for APIs, plugin and theme development, block editor), and more.

developer.wordpress.org

 

반응형

댓글