如果你只需要为最近50篇文章保留图像,我认为cron作业或WP cron不是你能做的最好的事情,在WordPress中,你可以知道一篇文章何时发布,你可以每次都运行一个例程,删除50篇之前发布的文章的图像。
这很简单,性能更好(如果无事可做,则什么也不做,无论是否有要删除的内容,cron作业都会运行)。
工作流程非常简单:
每次发布帖子时,获取第51个帖子id(按发布日期排序)
删除所有以该id为帖子父项的图像代码:add_action( \'save_post\', \'cleanup_old_post_images\', 10, 3 );
function cleanup_old_post_images( $post_ID, $post, $update ) {
if ( $update ) return; // do nothing on update
$postid51th = get51th_postid(); // see below
if ( ! empty( $postid51th ) && is_numeric( $postid51th ) ) {
delete_post_media( $postid51th ); // see below, function in OP
}
}
function get51th_postid() {
return $GLOBALS[\'wpdb\']->get_var(
"SELECT ID FROM " . $GLOBALS[\'wpdb\']->posts .
" WHERE post_type = \'post\' AND post_status = \'publish\' ORDER BY post_date DESC
LIMIT 50, 1"
);
}
function delete_post_media( $post_id ) {
$attachments = get_posts( array(
\'post_type\' => \'attachment\',
\'nopaging\' => TRUE,
\'post_parent\' => $post_id
) );
if ( empty( $attachments ) ) return; // added this line to prevent errors
foreach ( $attachments as $attachment ) {
if ( false === wp_delete_attachment( $attachment->ID ) ) {
// Log failure to delete attachment.
}
}
}
这适用于将代码放入站点后发布的帖子,但您可以编写run once函数来删除旧帖子的图像add_action( \'shutdown\', \'delete_older_attachments\' );
function delete_older_attachments() {
// run only on admin and use a transient to run once
if ( ! is_admin() || get_transient(\'get_older_postids\') ) return;
// the query to exclude last 50 posts
$latest_query = "SELECT ID FROM " . $GLOBALS[\'wpdb\']->posts .
" WHERE post_type = \'post\' AND post_status = \'publish\' ORDER BY post_date DESC
LIMIT 50"
);
// get older posts ids
$older_ids = $GLOBALS[\'wpdb\']->get_row(
"SELECT ID FROM " . $GLOBALS[\'wpdb\']->posts .
" WHERE post_type = \'post\' AND post_status = \'publish\'
AND ID NOT IN (" . $latest_query . ")"
);
// get attachments for older posts
if ( ! empty( $older_ids ) && is_array( $older_ids ) ) {
$attachments = $GLOBALS[\'wpdb\']->get_row(
"SELECT ID FROM " . $GLOBALS[\'wpdb\']->posts .
" WHERE post_type = \'attachments\'
AND post_parent IN (" . implode( \',\', $older_ids ) . ")"
);
}
if ( isset($attachments) && ! empty( $attachments ) && is_array( $attachments ) ) {
foreach ( $attachments as $attachment ) {
if ( false === wp_delete_attachment( $attachment ) ) {
// Log failure to delete attachment.
}
}
// set the transient to assure run once
set_transient( \'get_older_postids\', 1 );
}
}