自动删除附件和帖子

时间:2017-12-20 作者:Darlei Cordeiro

有谁知道有一个插件或函数可以在一定时间后自动从Wordpress删除帖子和媒体?

我有一个新闻网站,有两年多的新闻,我想删除,因为它很重,而且没有在服务器上保存的优势。

我买了专业版的批量删除,但插件没有激活,我正在寻找替代方案

1 个回复
SO网友:Serkan Algur

您可以通过WordPress Cron作业解决您的问题。我编写了这段代码和cron调度器。我还在本地主机上测试了这段代码。

如果将此代码添加到主题functions.php 你可以解决你的问题。Cron作业和功能每天都会工作,为您搜索旧帖子及其附件。

我的建议是,在实际网站上使用之前,先在本地主机上测试此代码。

<?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\' );

结束

相关推荐

how to edit attachments?

在将例如文件附加到帖子时,如何在事后编辑/删除它们?在帖子编辑器中找不到任何内容。谢谢