I am trying to delete the category dynamically when the plugin is deactivated but it is not deleting But it is adding on activation properly the only problem is deletion of category on deactivation.
function to add category
function add_category_on_activation(){
global $wpdocs_cat_id;
$wpdocs_cat = array('cat_name' => 'Event Category', 'category_description' => 'An Event Category to show all events', 'category_nicename' => 'events', 'category_parent' => '');
$wpdocs_cat_id = wp_insert_category($wpdocs_cat);
}
function to delete category
function delete_category_on_deactivation(){
wp_delete_category($wpdocs_cat_id);
}
Hook to add category
register_activation_hook( __FILE__, "add_category_on_activation" );
Hook to delete category
register_deactivation_hook( __FILE__, "delete_category_on_deactivation" );
I am trying to delete the category dynamically when the plugin is deactivated but it is not deleting But it is adding on activation properly the only problem is deletion of category on deactivation.
function to add category
function add_category_on_activation(){
global $wpdocs_cat_id;
$wpdocs_cat = array('cat_name' => 'Event Category', 'category_description' => 'An Event Category to show all events', 'category_nicename' => 'events', 'category_parent' => '');
$wpdocs_cat_id = wp_insert_category($wpdocs_cat);
}
function to delete category
function delete_category_on_deactivation(){
wp_delete_category($wpdocs_cat_id);
}
Hook to add category
register_activation_hook( __FILE__, "add_category_on_activation" );
Hook to delete category
register_deactivation_hook( __FILE__, "delete_category_on_deactivation" );
Share
Improve this question
asked Dec 19, 2019 at 16:54
Khurram AnsariKhurram Ansari
111 bronze badge
1 Answer
Reset to default 0You should save that category id in option table instead of set as global. Try below code which is helps you to delete that category on deactivation hook.
function add_category_on_activation(){
$wpdocs_cat = array('cat_name' => 'Event Category', 'category_description' => 'An Event Category to show all events', 'category_nicename' => 'events', 'category_parent' => '');
$wpdocs_cat_id = wp_insert_category($wpdocs_cat);
if($wpdocs_cat_id)
{
update_option('wpdocs_cat_id',$wpdocs_cat_id);
}
}
function delete_category_on_deactivation(){
$wpdocs_cat_id = get_option('wpdocs_cat_id');
if($wpdocs_cat_id)
{
wp_delete_category($wpdocs_cat_id);
delete_option('wpdocs_cat_id');
}
}
register_activation_hook( __FILE__, "add_category_on_activation" );
register_deactivation_hook( __FILE__, "delete_category_on_deactivation" );