antonio83
antonio83

Reputation: 454

Wordpress plugin uninstall.php

I am trying to write a simple plugin that, among other things, creates a custom post type. I have been searching everywhere but I have really no idea on how to write the uninstall function that delete the custom post type and all its entries from the db.

I have found this on the WordPress codex, but I don't understand what to do with it.. shame

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

$option_name = 'plugin_option_name';

delete_option( $option_name );

// For site options in multisite
delete_site_option( $option_name );  

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

Can anyone help?

Thanks in advance

Would this be correct?

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

    global $wpdb;

    $posts_table = $wpdb->posts;

    $query = "
        DELETE FROM wp_posts 
        WHERE post_type = 'messages' 
    ";

$wpdb->query($query);

Upvotes: 0

Views: 2936

Answers (1)

Adam Erstelle
Adam Erstelle

Reputation: 2513

The WP codex page http://codex.wordpress.org/Function_Reference/register_uninstall_hook has 2 important pieces of information, only 1 of which you list in your question. You do need to make sure that you register the hook.

That aside, if you want to remove all custom post data (regardless if it is upon uninstallation or as another person commented having a seperate button to remove data as many plugins do) you need to be sure to remove the postmeta records as well.

global $wpdb;
$cptName = 'messages';
$tablePostMeta = $wpdb->prefix . 'postmeta';
$tablePosts = $wpdb->prefix . 'posts';

$postMetaDeleteQuery = "DELETE FROM $tablePostMeta".
                      " WHERE post_id IN".
                      " (SELECT id FROM $tablePosts WHERE post_type='$cptName'";
$postDeleteQuery = "DELETE FROM $tablePosts WHERE post_type='$cptName'";

$wpdb->query($postMetaDeleteQuery);
$wpdb->query($postDeleteQuery);

Upvotes: 1

Related Questions