Last active
August 1, 2018 19:45
-
-
Save ai2ik/ce547ea15896c74715454acde689d6a3 to your computer and use it in GitHub Desktop.
Delete old wp posts by date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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