WordPress.org

Ready to get started?Download WordPress

Forums

using wp_delete_post to delete all posts from a custom post type (4 posts)

  1. robmuzo
    Member
    Posted 1 year ago #

    Hi Guys

    I need a function to find and delete all posts from a specific custom post type using wp_delete_post or another method if desirable.

    thanks

  2. robmuzo
    Member
    Posted 1 year ago #

    Found this but it gives a foreach error, any help?

    <?php
    // Get 50 custom post types pages, set the number higher if is not slow.
    
    $mycustomposts = get_pages( array( 'post_type' => 'name-of-post-type', 'number' => 50) );
       foreach( $mycustomposts as $mypost ) {
         // Delete's each post.
         wp_delete_post( $mypost->ID, true);
        // Set to False if you want to send them to Trash.
       }
    // 50 custom post types are being deleted everytime you refresh the page.?>
  3. Frumph
    Member
    Posted 1 year ago #

    $args = array(
    	'numberposts' => 50,
    	'post_type' =>'your_post_type'
    );
    $posts = get_posts( $args );
    if (is_array($posts)) {
       foreach ($posts as $post) {
    // what you want to do;
           wp_delete_post( $post->ID, true);
           echo "Deleted Post: ".$post->title."\r\n";
       }
    }

    You should not actually do the wp_delete_post without verifying the data output found with get_posts is what you want,

    you can do that with a var_dump($posts); after doing the get_posts

  4. robmuzo
    Member
    Posted 1 year ago #

    Thanks that did the job, what I wanted it for was to modify the CSV Importer plugin so that it deleted all existing posts first before importing the new ones as the plugin does not currently update existing just creates new. Not the most elegant of solutions but will do for now until I can find a solution for updating custom post types via CSV import.

Topic Closed

This topic has been closed to new replies.

About this Topic