i am new to plugin development in wordpress and i have have this simple test plugin that i am working on. The problem i am having is that the uninstall.php file does not appear to get trigger and as such the database entried i wish to remove remain after the plugin in uninstalled from the WordPress admin.
Plugin code:
defined( 'ABSPATH' ) or die( 'Looks like you made a wrong turn there buddy' );
class TestPlugin
{
function __construct() {
add_action( 'init', array( $this, 'create_post_type' ) );
}
function activate() {
// generate a CPT in case 'init' fails
$this->create_post_type();
// flush rewrite rules
flush_rewrite_rules();
}
function deactivate() {
// flush rewrite rules
flush_rewrite_rules();
}
function uninstall() {
// delete cpt
// delete all the plugin data from the DB
}
function create_post_type() {
register_post_type( 'acme_product', array( 'public' => true, 'label' => 'Acme Product' ) );
}
}
if ( class_exists( 'TestPlugin' ) ) {
$newTest = new TestPlugin();
}
// Activation
register_activation_hook( __FILE__, array( $newTest, 'activate' ) );
// Deactivation
register_activation_hook( __FILE__, array( $newTest, 'deactivate' ) );
Uninstall.php
/**
* Trigger this file on plugin uninstall
*
* @package TestPlugin
*/
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
die;
}
// Clear database stored data
//$acme_products = get_posts( array( 'post_type' => 'acme_product', 'numberposts' => -1 ) );
//
//foreach ( $acme_products as $acme_product) {
// wp_delete_post( $acme_product->ID, true );
//}
// Access the database via SQL
global $wpdb;
$wpdb->query( "DELETE FROM wp_posts WHERE post_type = 'acme_product'" );
$wpdb->query( "DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT id FROM wp_posts)" );
$wpdb->query( "DELETE FROM wp_term_relationships WHERE object_id NOT IN (SELECT id FROM wp_posts)" );
echo "UNINSTALL DAMMIT!!";
UPDATE:
I have tested the SQL query just to make sure it worked in phpMyAdmin, and it works fine.
i.e "DELETE FROM wp_posts WHERE post_type = 'acme_product'"