WP_DELETE_POST删除所有帖子,而不仅仅是过期的帖子

时间:2016-01-13 作者:The Sumo

我正在尝试设置一个cron作业,该作业可以删除过期的帖子(即过期日期<;今天的日期)。我在自定义帖子类型上有一个元框,可以为帖子添加到期日期。

我已设置cron作业,以每小时触发wp\\u delete\\u post。但是,它并不是只删除过期的帖子,而是删除自定义帖子类型中的所有帖子。

有人知道问题出在哪里吗?谢谢

add_action( \'wp\', \'delete_expired_adverts_daily\' );
function delete_expired_adverts_daily() {
    if ( ! wp_next_scheduled( \'delete_expired_adverts\' ) ) {
        wp_schedule_event( time(), \'hourly\', \'delete_expired_adverts\');
    }
}
add_action( \'delete_expired_adverts\', \'delete_expired_adverts_callback\' );

function delete_expired_adverts_callback() {
    $args = array(
        \'post_type\' => \'advert\',
        \'posts_per_page\' => -1
    );

    $query_ads = new WP_Query($args);
    if ($query_ads->have_posts()):
        while($query_ads->have_posts()): $query_ads->the_post();    

            $expiry_date = get_post_meta( $post_id, \'expires\', true);
            $today = date(\'d-m-Y\');

            $today_split = strtotime($today);
            $expiry_split = strtotime($expiry_date);

            if ($expiry_split < $today_split) {
                wp_delete_post(get_the_ID());
                //Use wp_delete_post(get_the_ID(),true) to delete the post from the trash too.                  
            }

        endwhile;
    endif;
}

1 个回复
最合适的回答,由SO网友:The Sumo 整理而成

如果其他人需要该代码,我就是这样解决的@pieter goosen是对的,我确实需要查询正确的帖子,但真正的诀窍是在运行帖子查询时匹配jquery datepicker中的日期格式。检查下面的日期格式,jquery是“yy-mm-dd”,php等效的是“Y-m-d”。

所以datepicker的js是:

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery(\'.ExDate\').datepicker({
            dateFormat: \'yy-mm-dd\'
        });
    });
</script>
cron函数是:

add_action( \'wp\', \'delete_expired_adverts_daily\' );
function delete_expired_adverts_daily() {
    if ( ! wp_next_scheduled( \'delete_expired_adverts\' ) ) {
        wp_schedule_event( time(), \'daily\', \'delete_expired_adverts\');
    }
}
add_action( \'delete_expired_adverts\', \'delete_expired_adverts_callback\' );

function delete_expired_adverts_callback() {

    $args = array (
                \'post_type\'    => \'advert\',
                \'meta_key\'     => \'expires\',
                \'meta_value\'   => date(\'Y-m-d\'),
                \'meta_compare\' => \'<=\',
            );

    $query_ads = new WP_Query($args);
    if ($query_ads->have_posts()):
        while($query_ads->have_posts()): $query_ads->the_post();    

            wp_delete_post(get_the_ID(), true);

        endwhile;
    endif;
}