How to automatically delete wordpress posts after x days ?

Muhatrima

Power Member
Joined
Dec 20, 2020
Messages
778
Reaction score
490
I have been searching for a way to delete all Wordpress posts including their media attachments after x days.

I have seen a couple plugins but they have either not being updated lately or are very new and not good for security reasons.

However I have found this code, Which is a cron that has to be run

Code:
DELETE FROM `wp_posts`
WHERE `post_type` = 'post'
AND DATEDIFF(NOW(), `post_date`) > 30

I am not sure, how to run this cron job on wordpress installation, so can anyone help either with how to run this cron or any other code that can be put into WordPress theme functions.php ?
 
For those of you who might benefit from it, I have found another temporary solution which fixes the problem i was adressing from a different view.

This will not run cron job, and will not delete posts after x days, but it rather deletes any posts that are more than x posts.

so i had to calcuate and estimate the monthly average of posts i make, so that i can delete any more posts that are older than one month in this way.

here is the code

Code:
add_action( 'publish_post', function ( $post_ID )
{
    $args = [
        'nopaging' => true,
        'fields'   => 'ids'
    ];
    $posts_array = get_posts( $args );
    // Make sure that we have post ID's returned
    if ( $posts_array ) {
        // Get all post ids after the 10th post using array_slice
        $delete_posts = array_slice( $posts_array, 1000 );
        // Make sure that we actually have post ID's in the $delete_posts array
        if ( $delete_posts ) {
            foreach ( $delete_posts as $delete_post )
                wp_delete_post( $delete_post, true );
        }
    }

where it says 1000 is the number of posts it will keep, so last 1000 posts will be kept always, and older will be deleted.

you can paste the code in the functions.php file of your theme.

and always take a backup before any changes.

any other better solution, will be apreciated.
 
This should have nothing to do with wp atall. Don't make your site heavier with yet another plugin. Instead have a script that connects to the same mysql db that your blog is in, and runs a sql query (the one in OP looks ok) to delete what you need.

Then place the script in cron using crontab -e.
 
Last edited:
post expirator is the best one here, but it does only expire and unpublish the posts, then I have to delete them my self, which is double work and still needs manual work

You could probably edit this code and change the action it performs on expiration. Instead of the unpublish, you run the DELETE query you posted above. Should be easy mod.
 
Back
Top