Delete expired posts in wordpress by date meta data custom field

↘锁芯ラ 提交于 2020-08-24 03:17:00

问题


---Resolved: Code Works as shown---

I have this piece of code that I think should work, but alas...

If anyone could take a peek and see if there something obvious. I have reviewed a lot of resources on the wordpress codex, but have tried all I can think of.

// 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' => 'post',
    'posts_per_page' => -1,
    'meta_key' => 'date',
    'meta_query' => array(
        array(
            'key' => 'date',
            'value' => $todays_date,
            'type' => 'DATE',
            'compare' => '<'
            )
    )
);
 $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' );
    }
}

回答1:


the_date() needs to be used within the Loop. Outside the Loop, it will return null. Use current_time() instead.

$todays_date = current_time('mysql'); // returns YYYY-MM-DD HH:MM:SS


来源:https://stackoverflow.com/questions/27386129/delete-expired-posts-in-wordpress-by-date-meta-data-custom-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!