Search code examples
phpwordpresspluginsuninstallation

Why is my WordPress plugin not deleting posts after uninstalling?


I am creating my plugin named ledproperty. I install it and create posts. Then I uninstall my plugin, but after reinstalling it, my old post reappears. I want that after the plugin is removed, everything that was created in the plugin is deleted. How can I fix this?

if (!defined('WP_UNINSTALL_PLUGIN')) exit; 

$ledproperty_args = array('post_type' => 'ledproperty', 'posts_per_page' => -1); 
$ledproperty_posts = get_posts($ledproperty_args); 

foreach ($ledproperty_posts as $post) { 
   wp_delete_post($post->ID, false); 
} 

Solution

  • If you want to execute some code after deactivating your plugin, you need to use the function register_deactivation_hook():

    register_deactivation_hook(__FILE__, 'ledproperty_plugin_deactivation');
    function ledproperty_plugin_deactivation() {
        $ledproperty_args = array('post_type' => 'ledproperty', 'posts_per_page' => -1, 'post_status' => 'any');
        $ledproperty_posts = get_posts($ledproperty_args);
    
        foreach ($ledproperty_posts as $post) {
            wp_delete_post($post->ID, false);
        }
    }
    

    Additionally, I recommend adding 'post_status' => 'any' to the args.