你真的确定要这样做吗?那么这些“旧”附件使用的所有帖子呢?对于用于“特色图片”等内容的附件,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 了解更多信息)。