0

Does anyone know of a plugin or function that automatically deletes after a certain period posts and media from Wordpress?

I have a news site and have news of more than 2 years that I want to delete because it weighs and has no advantage of keeping on the server.

I bought the pro version of Bulk Delete but the plugin does not activate, I'm looking for an alternative

1
  • If your purchased plugin doesn't work, I'd recommend checking in with their support streams.
    – Pat J
    Dec 20, 2017 at 15:49

1 Answer 1

1

You can solve your problem with a WordPress Cron Job. I wrote this code and cron scheduler. Also i tested this code on my localhost.

If you add this code to your theme's functions.php you can solve your problem. Cron job and function will work every day and search old posts and their attachments for you.

My advise, test this code on your localhost before using on actual website.

<?php 
// Please use this function carefully.
// Changes can't undone. Best regards from Serkan Algur :)
// Let the function begin
function delete_oldest_posts_salgur( ) {
    // We will collect posts from two years ago :)
    $args = array(
        'date_query' => array(
            array(
                'column' => 'post_date_gmt',
                'before' => '2 years ago', // change this definition for your needs
            ),
        ),
        'posts_per_page' => -1,
    );
    // Get posts via WP_Query
    $query = new WP_Query( $args );
    //We are doing this for 'foreach'
    $posts = $query->get_posts();   

        foreach($posts as $post){
            echo $post->ID;
            $args = array(
                'posts_per_page' => -1,
                'order'          => 'ASC',
                'post_mime_type' => 'image', // only for images. Look at https://codex.wordpress.org/Function_Reference/get_children
                'post_parent'    => $post->ID,
                'post_type'      => 'attachment',
            );

            $attachments = get_children( $args );

            if ( $attachments ) {
                foreach ( $attachments as $attachment ) {
                    wp_delete_attachment($attachment->ID,true); //If You Want to trash post set true to false
                }
            }
            wp_delete_post($post->ID,true); //If You Want to trash post set true to false
        }

}

// Problem Solver Cron Job definition
function cron_delete_oldest_posts_salgur() {
    if ( ! wp_next_scheduled( 'delete_oldest_posts_salgur' ) ) {
        wp_schedule_event( current_time( 'timestamp' ), 'daily', 'delete_oldest_posts_salgur' );
    }
}
add_action( 'wp', 'cron_delete_oldest_posts_salgur' );

Not the answer you're looking for? Browse other questions tagged or ask your own question.