卸载我的插件时似乎不会触发uninstall.php

时间:2017-11-27 作者:Frederick M. Rogers

我是wordpress中插件开发的新手,我正在开发这个简单的测试插件。我遇到的问题是卸载。php文件似乎没有触发,因此我希望删除的以数据库为中心的插件在从WordPress管理员卸载后仍然存在。

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:我测试了SQL查询,以确保它在phpMyAdmin中工作,并且工作正常。

i、 e类"DELETE FROM wp_posts WHERE post_type = \'acme_product\'"

2 个回复
SO网友:Drupalizeme

除了echo一个字符串(这解释了我们失败)和使用硬代码前缀之外,我认为卸载没有任何问题。

以下代码已使用最新版本的WordPress在本地进行了测试。

// Access the database via SQL
global $wpdb;
$wpdb->query( "DELETE FROM {$wpdb->prefix}posts WHERE post_type = \'acme_product\'" );
$wpdb->query( "DELETE FROM {$wpdb->prefix}postmeta WHERE post_id NOT IN (SELECT ID FROM {$wpdb->prefix}posts)" );
$wpdb->query( "DELETE FROM {$wpdb->prefix}term_relationships WHERE object_id NOT IN (SELECT ID FROM {$wpdb->prefix}posts)" );


// echo "UNINSTALL DAMMIT!!";

SO网友:Johansson

你的两个钩子都是register_activation_hook(). 为了挂接插件的停用,您应该使用register_deactivation_hook() 相反

此外,不应将此挂钩与register_uninstall_hook(), 最好在卸载插件后触发。

您可以在Plugin Handbook.

结束

相关推荐

Virtual Pages plugins

我很难让插件正常工作Virtual Pages (WordPress插件可简化虚拟页面的创建)我确实进行了编辑,根据查询创建了一个循环。add_action( \'gm_virtual_pages\', function( $controller ) { /* Creating virtuals pages for companies */ $args = array( \'post_type\' => array(\'companies\',), \'post_status\'