自动删除超过x天的附件

时间:2017-03-05 作者:TravelWhere

是否有方法自动删除早于x天的附件?因为我时不时地会有超过1000万张图像,数据库变得如此庞大,以至于由于cpu有限,网站速度变慢

1 个回复
最合适的回答,由SO网友:Paul \'Sparrow Hawk\' Biron 整理而成

你真的确定要这样做吗?那么这些“旧”附件使用的所有帖子呢?对于用于“特色图片”等内容的附件,WP将为您提供。但是,对于post\\u内容中附件的使用,例如。

<img src=\'img_attachment_url\' />
<a href=\'pdf_attachment_url\'>download PDF</a>
你最终会得到“断开”的链接。

但是,如果你真的确定,你可以使用WP-Cron.

一个快速而肮脏的解决方案,可能无法完成您需要它做的所有事情,它看起来像(note: 我还没有实际测试这段代码,因为很明显,我不想删除我当前维护的任何站点中的旧附件):

    // using this $num_days global is a kind of a hack but it makes sure that
    // all of the places where we need X we have the same value
    // if you were to encapsulate this code into a class
    // then you could set it as a class const
    global $num_days ;
    $num_days = 10 ;

    // hook into cron_scedules to add our "every X days"
    add_filter (\'cron_schedules\', \'add_my_schedule\') ;
    // add our cron hook
    add_action (\'my_cron_hook\', \'my_cron_func\') ;

    // if our hook is not currently scheduled, then schedule it
    if (!wp_next_scheduled (\'my_cron_hook\')) {
        wp_schedule_event (time (), "$num_days_days", \'my_cron_hook\') ;
    }

    /**
     * add our "every X days" to the available schedules
     */
    function
    add_my_schedule ($schedules)
    {
        global $num_days ;

        $schedules["$num_days_days"] = array (
            \'interval\' => $num_days * DAY_IN_SECONDS,
            \'display\'  => esc_html__("Every $num_days Days"),
            ) ;

        return ($schedules) ;
    }

    /**
     * this is the func that will be called when the cron job executes
     */
    function
    my_cron_func ()
    {
        global $num_days, $post ;

        // query for attachments added more than $num_days ago
        $args = array (
            \'post_type\' => \'attachment\',
            \'post_status\' => \'inherit\',
            \'date_query\' => array (
                // see https://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters
                // for more info on this \'before\' date_query syntax
                \'before\' => "$num_days days ago",
                ),
            \'posts_per_page\' => -1,
            ) ;
        $old_attachments = new WP_Query ($args) ;

        while ($old_attachments->have_posts ()) {
            $old_attachments->the_post () ;

            wp_delete_attachment ($post->ID, true) ;
            }

        // probably not necessary to call wp_reset_postdata(),
        // since we\'re in a cron job, but doesn\'t hurt
        wp_reset_postdata () ;
    }
确保在不再需要cron作业时/如果不再需要它,则取消其计划。我将把它作为一个“读者练习”来了解如何做到这一点(提示,请参见Unscheduling Tasks 了解更多信息)。

相关推荐

Extra "uploads" added in path

虽然这与高级自定义字段相关,但此函数使用所有本机WP特性,因此我认为在这里询问这一点是合适的。路径中的额外“/上传/”来自何处?在后端,我看到了上传文件的正确链接(domain.com/wp-content/member-files/name.pdf),但在前端,URL在路径(domain.com/wp-content/uploads/member-files/name.pdf)中显示了额外的“/uploads/”,当然为文件生成了404。// file upload to custom location