Skeleton Code

Delete Old WordPress Posts Within a Certain Timeframe

Place in functions.php
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' => '-1 years'
)//date query for before 1 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 want old posts to go to trash
// wp_delete_post(get_the_ID(),true); //use this function if you want old posts to skip trash and force delete
}
} else {
// no posts found
return false;

}
die();
// Restore original Post Data
wp_reset_postdata();

}
add_action('init','get_delete_old_post');