5

I have tried dbDelta and $wpdb->query, they does not work. Does anyone has any ideas?

1
  • What is the error? You can dump it with the following call right after you executed the statement: $e = $wpdb->query($sql); die(var_dump($e));
    – Thomas
    Commented Apr 26, 2012 at 8:47

3 Answers 3

12

As try today, truncate is WAY BETTER that DELETE, because DELETE broke the site, and trucate just empty the table, here is the working code :

global $wpdb;

$wpdb->query('TRUNCATE TABLE wp_posts');
0

According to this forum entry, truncate does not work. I would guess that since it's such a destructive query, that it's filtered by the class. There is also this Trac Post, which if I am reading it right, disallows DDL statements.

5
  • Well, maybe I use DELETE instead of truncate.
    – goodseller
    Commented Apr 26, 2012 at 14:51
  • @goodseller Not sure what you're trying to do, so it might not be important to you--but note that DELETE does not reset any auto-incrementing columns. So even though your table will be empty, the next item ID will pick up where the last auto- incremented value left off.
    – MathSmath
    Commented Apr 26, 2012 at 19:53
  • @MathSmath Yeah~ That's true, so true. However is there any way to do so?
    – goodseller
    Commented Apr 27, 2012 at 4:02
  • I found it: $wpdb->query("ALTER TABLE tableName AUTO_INCREMENT=0") Thanks @MathSmath :)
    – goodseller
    Commented Apr 27, 2012 at 5:37
  • 1
    1. linked forum entry code did not work because of a typo. 2. trac ticket just talks about return values from ddl statements.
    – skndstry
    Commented Sep 13, 2016 at 9:03
0

I know there are similar answers above but in the above answers, the table wp_post used if by mistake someone uses that code will lose his all posts.

So sharing a correct way to truncate.

   global $wpdb;
   $table_name = $wpdb->base_prefix.'name_of_table_without_prefix';
   $wpdb->query("TRUNCATE TABLE $table_name");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.