使过帐过期至草稿日期-选取器自定义字段

时间:2021-04-11 作者:Juraj

需要在达到ACF日期选择器字段中的日期时将过帐设置为草稿。这是我正在使用的代码:

// expire offer posts on date field.
if (!wp_next_scheduled(\'expire_posts\')){
  wp_schedule_event(time(), \'twicedaily\', \'expire_posts\'); // this can be hourly, twicedaily, or daily
}

add_action(\'expire_posts\', \'expire_posts_function\');

function expire_posts_function() {
    $today = date(\'Ymd\');
    $args = array(
        \'post_type\' => array(\'event\'), // post types you want to check
        \'posts_per_page\' => -1 
    );
    $posts = get_posts($args);
    foreach($posts as $p){
        $expiredate = get_field(\'ev_date\', $p->ID, false, false); // get the raw date from the db
        if ($expiredate) {
            if($expiredate < $today){
                $postdata = array(
                    \'ID\' => $p->ID,
                    \'post_status\' => \'draft\'
                );
                wp_update_post($postdata);
            }
        }
    }
}
它不起作用。我做错了什么?这是我的字段设置:

Date picker field settings

和来源:ACF forum

1 个回复
SO网友:Abhik

ACF将值另存为Ymd 在数据库中设置格式,而不考虑显示和返回格式。您所需要的只是一个元查询来获取正确的帖子。

function expire_posts_function() {
    
    //Get Expired Posts only
    $expired_posts = get_posts(arrasy(
        \'post_type\' => \'event\',
        \'posts_per_page\' => -1,
        \'post_status\' => \'publish\',
        \'meta_query\' => array(
            array(
                \'key\' => \'ev_date\',
                \'value\' => date(\'Ymd\'),
                \'compare\' => \'<\',
            ),
        ),
    ));
    
    //Loop through the posts and set status
    if ( $expired_posts ) {
        foreach( $expired_posts as $expired_post ) {
            wp_insert_post(array(
                \'ID\' => $expired_post->ID,
                \'post_status\' => \'draft\',
            ));
        }
    }
}

相关推荐