plugins – How to delete posts older than one year with post meta, post attachments and recordsdata?

[ad_1]

I’ve already answered that sort of query here but you need to delete post_meta too. Here is your code. Please check this on localhost first.

<?php

// Please use this perform carefully.
// Changes can't undone. Best regards from Serkan Algur :)
// Let the perform begin
perform 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 on your wants
            ),
        ),
        'posts_per_page' => -1,
    );
    // Get posts through WP_Query
    $question = 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' => 'picture', // just for photos. Look at https://codex.wordpress.org/Function_Reference/get_children
                'post_parent'    => $post->ID,
                'post_type'      => 'attachment',
            );

        $attachments = get_children($args);
        $post_metas = get_post_meta($post->ID); // Get all post metas

        if ($post_metas) {
            foreach ($post_metas as $key => $pmeta) { //delte all of them
                delete_post_meta($post->ID, $key);
            }
        }

        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
perform 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');

[ad_2]
Source link

Leave a Reply