How to Delete Old Post in WordPress

How to Delete Old Post in WordPress
173 Views

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();
}
?>
Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.