• Resolved Guido

    (@guido07111975)


    Hi,

    When I uninstall my plugin I want to remove all events (custom post type) and event postmeta from database. I use this code in uninstall.php for that:

    // Delete events + metadata
    global $wpdb;
    $wpdb->query( "DELETE FROM {$wpdb->posts} WHERE post_type IN ( 'event' );" );
    $wpdb->query( "DELETE meta FROM {$wpdb->postmeta} meta LEFT JOIN {$wpdb->posts} posts ON posts.ID = meta.post_id WHERE posts.ID IS NULL;" );

    Taken from Woocommerce, and it works like a charm.
    My question: the second query removes the event postmeta, but I don’t understand how it’s part of the first query? I mean, why does it only remove postmeta from events and not from all posts?

    Guido

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator bcworkz

    (@bcworkz)

    Hello again!

    The key is ON posts.ID = meta.post_id WHERE posts.ID IS NULL.

    This means match meta entries whose post_id has no match in posts.ID. The SQL engine tries to match IDs, but fails because of the deleted posts. It will in fact delete meta from deleted posts other than ‘event’ type, which shouldn’t be a problem.

    It’s a rather clever SQL trick even though it’s difficult to follow the logic. Those WooThemes devs are pretty smart ??

    Thread Starter Guido

    (@guido07111975)

    And thanks again! Guess you’re the only one responding here ;-)?

    I notice I was thinking in the right direction: there’s no direct relation between the both ??

    I decided to use a default WordPress function to remove the postmeta:

    // Delete custom post meta
    delete_post_meta_by_key( 'mykey1' );
    delete_post_meta_by_key( 'mykey2' );
    
    // Delete events
    global $wpdb;
    $wpdb->query( "DELETE FROM {$wpdb->posts} WHERE post_type = 'event' " );

    Guido

    Moderator bcworkz

    (@bcworkz)

    Heh, I sometimes feel like this sub-forum is my own little corner of www.remarpro.com but in fact there are several regulars here that answer questions. We all skip over questions for various reasons, usually “I don’t know the answer”, but you can imagine some other reasons that can come up as well.

    I personally try to answer all questions in this sub-forum if at all possible. The other forums are way too busy for such a goal. I often don’t know the answer immediately but have a good idea on how to find out, so answering is a good educational opportunity for me as well ??

    Thread Starter Guido

    (@guido07111975)

    I was doing the same thing for another WP forum but after a while I felt I had an obligation to respond there > that’s not good. So as long as you have fun responding here: nice and many thanks ??

    Guido

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Uninstall plugin: delete events and postmeta from database’ is closed to new replies.