How to Delete Old Post in WordPress

How to Delete Old Post in WordPress
440 Views
0
(0)

We want to delete old post in easy way, Add the following code to your current themes functions.php file and reload your page and see your post may have been deleted.

<?php
add_action( 'init', 'cxc_get_delete_old_post' );

function cxc_get_delete_old_post() {
    // WP_Query arguments
	$args = array(
		'fields' => 'ids',
		'post_type'      =>  'post', //specify your post type here.
		'posts_per_page' => '-1',    //fetch all posts,
		'date_query'     => array(
			'column'  => 'post_date',
			'before'   => date( "Y-m-d H:i:s", strtotime( '-1 year' ) ), //specify your time here.
		) 
	);
	
	// The Query
	$query = new WP_Query( $args );

    // The Loop
	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			//delete post code
            //wp_trash_post( get_the_ID() );  use this function if you have custom post type
            wp_delete_post( get_the_ID(), true ); //use this function if you are working with default posts
        }    
    } else {
    	echo 'no posts found';
    	return false;
    }
    die();
    // Restore original Post Data
    wp_reset_postdata();
}
?>

How useful was this blog?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this blog.

As you found this blog useful...

Follow us on social media!

We are sorry that this blog was not useful for you!

Let us improve this blog!

Tell us how we can improve this blog?

Leave a comment

Your email address will not be published. Required fields are marked *