如何使用WP帖子状态转换来处理帖子的到期日期


How to use WP Post Status Transitions to handle posts expiration dates

我是新手& &;date/time/PHP这些东西真让我头疼。

1)如何使用WP Post Status Transitions来注册准确的日期& &;post状态变化的时间(让我们命名为valueX)?

2)现在我从我的主题选项(valueY)带来其他价值-它要么是一个时期(例如30天)或日期&时间

3)如何计算valueXvalueY得到valueZ ->那是日期&当帖子更改草稿或删除自己的时候!

这最终应该如何工作:

  1. 我在主题选项中有2个输入,1是草稿生命典当,1是发布后生命典当(输入是int -值是分钟或小时)
  2. 如果你发布帖子,它会保存这个事件的日期和时间。
  3. 将主题选项值(发布后生命典当int)添加到该时间,结果是发布更改草案的日期
  4. 如果时间到了,把post改为draft(节省时间)
  5. 添加主题选项值(draft lifespawn int)到该时间,结果是草案被删除的日期
  6. 如果时机成熟,请删除草案

听起来很合乎逻辑,但是我没有足够的技能来做这件事。

我的代码:

注意:

  • 我把它分成2部分,以便于阅读-第一个是发布的帖子草案和第二个代码是草稿要删除。每一步都有注释。
  • 逻辑是,如果你编辑发布的帖子,它不应该重置定时器如果你在任何时候把post改为draft,它就会开始draft
  • 这似乎太长太复杂了…这就是为什么我没有首先添加它。我相信这件事会容易得多方式。
  • 我使用WP发布时间和编辑时间,因为我不知道如何节省时间,使用WP Post Status Transitions将该特定时间的日期转换为分离值。

PUBLISH -> DRAFT

    if ( !function_exists('tt_icon_time_left') ) {
      function tt_icon_time_left() {
        //Set Timezone To Local
        date_default_timezone_set('Europe/London');
        // Check post status
        if ( get_post_status($post->ID) == "publish" ) {
          //Get Property Publish Date
          $time_post_published = get_the_time( 'H:i:s d.m.Y' );
          // Get Active Post Expiration Value From Theme Options
          global $theme_option;
          $post_time_integer = $theme_option['post-time-left'];
          // Get Active Post Expiration Value From Meta
          $single_post_time_left = get_post_meta( get_the_ID(), 'post_time_left', true );
          // Decide If Theme Options Or Meta Active Post Expiration Value
          if ( $single_post_time_left <= 0 && $post_time_integer <= 0 ) {
            $post_time = 0;
          }
          else if ( $single_post_time_left < $post_time_integer && $single_post_time_left > 0 || $single_post_time_left > $post_time_integer ) {
            $post_time = $single_post_time_left;
          }
          else {
            $post_time = $post_time_integer;
          }
          // Active Post Expiration Value To Seconds
          $post_time_seconds = $post_time * 86400;
          // Active Post Age In Seconds
          $active_post_age = strtotime($time_post_published);
          $active_post_age = time() - $active_post_age;
          // Calculate Active Post Expiration Date
          $post_expiration_time = date( 'H:i:s d.m.Y' ,strtotime( $time_post_published ) + $post_time_seconds );
          // Show Icon And Time Left Until Active Post Changes To Draft In Tooltip ONLY SHOWN IN SUBMIT LISTING
          if ( $post_time > 0 && $active_post_age <= $post_time_seconds ) {
            global $post;
            if ( is_page_template( 'template-post-submit-listing.php' ) ) { 
              return '<i class="fa fa-clock-o" data-toggle="tooltip" title="' . __( 'Post expires on ' .  $post_expiration_time, 'tt' ) . '"></i>'; 
            }
            else {
              return false;
            }
          }

DRAFT -> DELETE

          // Change Active Post To Draft If Time Is Up
          else if ( $post_time > 0 && $active_post_age > $post_time_seconds ) {
            $postt['post_status'] = 'draft';
            wp_update_post($post);
          }
          else {
           return false; 
          }
        }
        // Chech post status
        else if ( get_post_status($post->ID) == "draft" ) {
          $time_post_published = $publish_time;
          // Get Draft Expiration Value From Theme Options
          global $theme_option;
          $draft_time_integer = $theme_option['draft-time-left'];
          // Get Draft Expiration Value From Meta
          $single_draft_time_left = get_post_meta( get_the_ID(), 'draft_time_left', true );
          // Decide If Theme Options Or Meta Draft Expiration Value
          if ( $single_draft_time_left <= 0 && $draft_time_integer <= 0 ) {
            $draft_time = 0;
          }
          else if ( $single_draft_time_left < $draft_time_integer && $single_draft_time_left > 0 || $single_draft_time_left > $draft_time_integer ) {
            $draft_time = $single_draft_time_left;
          }
          else {
            $draft_time = $draft_time_integer;
          }
          // Draft Expiration Value To Seconds
          $draft_time_seconds = $draft_time * 86400;
          // Draft Age In Seconds
          $draft_age = strtotime($time_property_modified);
          $draft_age = time() - $draft_age;
          // Calculate Draft Expiration Date
          $draft_expiration_time = date( 'H:i:s d.m.Y' ,strtotime( $time_property_modified ) + $draft_time_seconds );
          // Show Icon And Time Left Until Draft Gets Deleted In Tooltip ONLY IN SUBMIT LISTING
          if ( $draft_time && $draft_age <= $draft_time_seconds ) {
            global $post;  
            if ( is_page_template( 'template-property-submit-listing.php' ) ) { 
              return '<i class="fa fa-clock-o" data-toggle="tooltip" title="' . __( 'Property gets deleted on ' . $draft_expiration_time , 'tt' ) . '"></i>';
            }
            else {
              return false;
            }
          }
          // Delete Draft If Time Is Up
          else if( $draft_time && $draft_age > $draft_time_seconds ) {
                // I got this
          }
        }
        else {
          return false;
        }
      }
    }

1)如何使用WP Post Status Transitions来注册准确的日期&时间post状态更改(让我们将其命名为valueX)?

在我看来,处理这个问题的更好的方法不是使用Post Transition状态钩子,而是使用Wordpress Cron——因为当管理员要更改Post状态时,这些钩子将被调用。我们将只使用一个Post Transition Status来注册第一次发布的在名为firstPublishTime:

的自定义字段中。
add_action('transition_post_status', 'first_publish_time_register', 10, 3);
function first_publish_time_register($new, $old, $post) {
    if ($new == 'publish' && $old != 'publish' && $post->post_type == 'post') { // change this to whatever post type you like
        $firstPublishTime = get_post_meta($post->ID, 'firstPublishTime', true);
        if(empty($firstPublishTime)) {
            // First time the post is publish, register the time
            add_post_meta($post->ID, 'firstPublishTime',  strftime('%F %T'), true);
        }
    }
}

2)现在我把其他值从我的主题选项(valueY) -它是一段时间(如30天)或日期时间

对于下一部分,我将考虑您有两个主题选项,两个周期:一个用于"发布到草案"延迟,名为your_theme_option1,另一个用于"草案到删除延迟",名为your_theme_option2;YY-MM-DD-HH-MM-SS格式。例如,00-00-30-00-00-00表示30天,00-01-00-00-00-00表示一个月,等等。

3)如何用valueX和valueY计算得到valueZ ->这就是日期& &;时间当帖子删除自己!

这就是乐趣所在。我们将注册一个每小时执行一次的WP Cron (请注意,它不是服务器Cron,如果在小时内没有人访问您的网站,则不会被处理)。下面的代码将每小时执行一次cron_postStatus()函数:

register_activation_hook(__FILE__, 'cron_postStatus_activation');
add_action('postStatus_event', 'cron_postStatus');
function cron_postStatus_activation() {
    wp_schedule_event(time(), 'hourly', 'postStatus_event');
}

现在是最重要的部分:

function cron_postStatus() {
    // Get the theme options
    $published_to_draft_delay = get_option('your_theme_option1');
    $draft_to_deleted_delay     = get_option('your_theme_option2');
    if(!$published_to_draft_delay || !$draft_to_deleted_delay) {
        return new WP_Error('broke', __('Theme options unavailable'));
    }
    $published_to_draft_delay = explode('-', $published_to_draft_delay);
    $draft_to_deleted_delay     = explode('-', $draft_to_deleted_delay);
    $published_to_draft_delay = new DateInterval(
        'P'.$published_to_draft_delay[0].'Y'.
        $published_to_draft_delay[1].'M'.
        $published_to_draft_delay[2].'D'.
        'T'.$published_to_draft_delay[3].'H'.
        $published_to_draft_delay[4].'M'.
        $published_to_draft_delay[5].'S'
    );
    $draft_to_deleted_delay     = new DateInterval(
        'P'.$draft_to_deleted_delay[0].'Y'.
        $draft_to_deleted_delay[1].'M'.
        $draft_to_deleted_delay[2].'D'.
        'T'.$draft_to_deleted_delay[3].'H'.
        $draft_to_deleted_delay[4].'M'.
        $draft_to_deleted_delay[5].'S'
    );
    $now = new DateTime();
    // Get all the unpublished posts
    $unpublished_posts = new WP_Query(array(
        'posts_per_page'    => -1,
        'post_type'         => 'post', // change this to whatever post type you like
        'meta_key'          => 'expirationDate',
        'post_status'       => 'draft'
    ));
    while($unpublished_posts->have_posts()) {
        $unpublished_posts->the_post();
        $expirationDate = get_post_meta(get_the_ID(), 'expirationDate', true);
        if(!empty($expirationDate)) {
            // Date comparison
            $dt = new DateTime($expirationDate);
            $dt->add($draft_to_deleted_delay);
            if($dt > $now) {
                // Expiration date reached, unpublish the post
                wp_delete_post(get_the_ID(), true);
            }
        }
    }
    // Get all the published posts
    $published_posts = new WP_Query(array(
        'posts_per_page'    => -1,
        'post_type'         => 'post', // change this to whatever post type you like
        'meta_key'          => 'firstPublishTime'
    ));
    while($published_posts->have_posts()) {
        $published_posts->the_post();
        $first_publish = get_post_meta(get_the_ID(), 'firstPublishTime', true);
        if(!empty($first_publish)) {
            // Date comparison
            $dt = new DateTime($first_publish);
            $dt->add($published_to_draft_delay);
            if($dt > $now) {
                // Expiration date reached, unpublish the post
                wp_transition_post_status('draft', 'publish', $published_posts->post);
                add_post_meta($post->ID, 'expirationDate',  strftime('%F %T'), true);
            }
        }
    }
    wp_reset_postdata();
}

在这里,我决定使用DateInterval,以便轻松地操作截止日期。首先,我们从wp_options获得截止日期选项,在DateInterval对象中构建它们,然后获得当前时间。然后我们将执行两个查询,一个用于草稿,另一个用于已发布的帖子。对于草稿,我们检查是否有expirationDate元值,如果有并且我们达到了删除时间,我们从数据库中删除该帖子。对于已发布的帖子,如果达到截止日期,我们将状态更改为草稿,并添加一个名为expirationDate的自定义值—这是为了区分cron和管理的"发布到草稿"更改。

请注意这是一个未经测试的代码

更新

下面是一个函数,你可以使用它来获取过期时间:

function getExpirationInfos($post) {
    // Get all informations
    $first_publish = get_post_meta($post->ID, 'firstPublishTime', true);
    $expirationDate = get_post_meta($post->ID, 'expirationDate', true);
    if(empty($first_publish)) {
        return '';
    }
    $published_to_draft_delay = get_option('your_theme_option1');
    $draft_to_deleted_delay     = get_option('your_theme_option2')
    $published_to_draft_delay = explode('-', $published_to_draft_delay);
    $draft_to_deleted_delay     = explode('-', $draft_to_deleted_delay);
    $published_to_draft_delay = new DateInterval(
        'P'.$published_to_draft_delay[0].'Y'.
        $published_to_draft_delay[1].'M'.
        $published_to_draft_delay[2].'D'.
        'T'.$published_to_draft_delay[3].'H'.
        $published_to_draft_delay[4].'M'.
        $published_to_draft_delay[5].'S'
    );
    $draft_to_deleted_delay     = new DateInterval(
        'P'.$draft_to_deleted_delay[0].'Y'.
        $draft_to_deleted_delay[1].'M'.
        $draft_to_deleted_delay[2].'D'.
        'T'.$draft_to_deleted_delay[3].'H'.
        $draft_to_deleted_delay[4].'M'.
        $draft_to_deleted_delay[5].'S'
    );
    $now = new DateTime();
    // Calculate time left
    if($post->post_status == 'publish') {
        $dt = new DateTime($first_publish);
        $dt->add($published_to_draft_delay);
    } else {
        if(empty($expirationDate)) {
            return '';
        }
        $dt = new DateTime($expirationDate);
        $dt->add($draft_to_deleted_delay);
    }
    $et = date_diff($dt, $now);
    $expirationTimeString = (($et->y > 0) ? $et->format('y') . ' years, ' : '') .
        (($et->m > 0) ? $et->format('y') . ' months, ' : '') .
        (($et->d > 0) ? $et->format('m') . ' days, ' : '') .
        (($et->h > 0) ? $et->format('h') . ' hours, ' : '') .
        (($et->i > 0) ? $et->format('i') . ' minutes, ' : '') .
        (($et->s > 0) ? $et->format('s') . ' seconds, ' : '');
    $expirationTimeString = substr($expirationTimeString, 0, -2);

    // Return HTML
    return '<i class="fa fa-clock-o" data-toggle="tooltip" title="' . __( 'Property gets deleted on', 'tt' ) . ' ' . $expirationTimeString . '"></i>';
}

然后在模板中执行echo getExpirationInfos($post);来显示截止日期