我使用以下代码删除状态为“过期”的自定义帖子(感谢Jamie Keefer). 第三方插件将帖子设置为“过期”。用户只能通过前端访问其帖子(广告)。
我的问题是:how to delete them after a number of days after they expired if post authors don\'t republish them? 此外,如果您能就如何改进此代码提出建议,我将不胜感激。
// expired_post_delete hook fires when the Cron is executed
add_action( \'expired_post_delete\', \'delete_expired_posts\' );
// This function will run once the \'expired_post_delete\' is called
function delete_expired_posts() {
$todays_date = current_time(\'mysql\');
$args = array(
\'post_type\' => \'advert\',
\'post_status\' => \'expired\',
\'posts_per_page\' => -1
);
$posts = new WP_Query( $args );
// The Loop
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
wp_delete_post(get_the_ID());
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
}
// Add function to register event to WordPress init
add_action( \'init\', \'register_daily_post_delete_event\');
// Function which will register the event
function register_daily_post_delete_event() {
// Make sure this event hasn\'t been scheduled
if( !wp_next_scheduled( \'expired_post_delete\' ) ) {
// Schedule the event
wp_schedule_event( time(), \'daily\', \'expired_post_delete\' );
}
}
UPDATE
以下是如何将帖子设置为“过期”:
add_action( \'adverts_event_expire_ads\', \'adverts_event_expire_ads\' );
/**
* Expires ads
*
* Function finds Adverts that already expired (value in _expiration_date
* meta field is lower then current timestamp) and changes their status to \'expired\'.
*
* @since 0.1
* @return void
*/
function adverts_event_expire_ads() {
// find adverts with status \'publish\' which exceeded expiration date
// (_expiration_date is a timestamp)
$posts = new WP_Query( array(
"post_type" => "advert",
"post_status" => "publish",
"meta_query" => array(
array(
"key" => "_expiration_date",
"value" => current_time( \'timestamp\' ),
"compare" => "<="
)
)
) );
if( $posts->post_count ) {
foreach($posts->posts as $post) {
// change post status to expired.
$update = wp_update_post( array(
"ID" => $post->ID,
"post_status" => "expired"
) );
} // endforeach
} // endif
}