Skip to content

Instantly share code, notes, and snippets.

@ai2ik
Last active August 1, 2018 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ai2ik/ce547ea15896c74715454acde689d6a3 to your computer and use it in GitHub Desktop.
Save ai2ik/ce547ea15896c74715454acde689d6a3 to your computer and use it in GitHub Desktop.
Delete old wp posts by date
function get_delete_old_post()
{
// WP_Query arguments
$args = array(
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => array(
'post'
) , //post type if you are using default than it will be post
'posts_per_page' => '-1', //fetch all posts,
'date_query' => array(
'column' => 'post_date',
'before' => '-2 years'
) //date query for before 2 years you can set date as well 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
{
// no posts found
return false;
}
die();
// Restore original Post Data
wp_reset_postdata();
}
add_action('init', 'get_delete_old_post');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment