【问题标题】:Wordpress - set post to draft by date-picker custom fieldWordpress - 通过日期选择器自定义字段将帖子设置为草稿
【发布时间】:2022-04-03 07:40:13
【问题描述】:

当从 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);
            }
        }
    }
}

我做错了什么?这是我的字段设置:

来源:

ACF forum

【问题讨论】:

    标签: wordpress cron advanced-custom-fields custom-post-type


    【解决方案1】:

    将您的日期格式 'j.n.Y' 转换为 Ymd

    // 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 = date( 'Ymd', strtotime( get_field( 'ev_date', $p->ID ) ) ); // get the raw date from the db
            if ($expiredate) {
                if($expiredate < $today){
                    $postdata = array(
                        'ID' => $p->ID,
                        'post_status' => 'draft'
                    );
                    wp_update_post($postdata);
                }
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      看起来您试图将变量 $today(格式为 Ymd - 例如 20210411)与存储在 $expiredate 中的字段信息(格式为 j.n.Y)进行比较我认为您应该将 ACF 上的返回格式更改为Ymd 使其匹配。

      确实,将 false 传递给 get_field() 应该返回未格式化的字段,但您似乎向 get_field() 发送了太多参数,最多只能获得 3 个参数:

      get_field($selector, [$post_id], [$format_value]);
      

      我会尝试:

      $expiredate = get_field('ev_date', $p->ID);
      

      并将ACF返回格式改为Ymd

      【讨论】:

        【解决方案3】:

        我做过类似的事情,如果你将 ACF 返回格式设置为 U 以进行通用,它就可以工作。这样时区就不会造成问题。

        【讨论】:

          猜你喜欢
          • 2014-04-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-30
          • 2016-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多