jjzjj

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

coder 2024-04-18 原文

我是这个 & date/time/PHP 的新手,这让我的大脑很受伤。

1) 如何使用WP Post Status Transitions注册发布状态更改的确切日期和时间(我们将其命名为 valueX)?

2) 现在我从我的主题选项 (valueY) 中获取其他值 - 它可以是一个时间段(例如 30 天)或日期和时间

3) 如何用valueXvalueY 计算得到valueZ -> 那就是日期&帖子更改为草稿或自行删除的时间!

这最终应该如何工作:

  1. 我在主题选项中有 2 个输入,1 个用于 draft lifespawn,1 个用于发布后 lifespawn(输入为整数 - 值为分钟或小时)
  2. 如果您发布帖子,它会保存此事件的日期和时间。
  3. 将主题选项值(发布后 lifespawn int)添加到该时间,结果是草稿更改后的日期
  4. 如果那个时候到了,将帖子更改为草稿(并节省那个时间)
  5. 将主题选项值(draft lifespawn int)添加到那个时间,结果是 draft 被删除的日期
  6. 如果那个时候删除草稿

这一切听起来很合乎逻辑,但我没有足够的技能来做到这一点。

我的代码:

注意:

  • 为了便于阅读,我将其分为两部分 - 第一部分是发布后草稿,第二部分是代码 要删除的草稿。每一步都有评论。
  • 逻辑是,如果您编辑已发布的帖子,它不应该重置计时器 如果您在任何给定时间将帖子更改为草稿,它将开始草稿 处理并停止已发布的后期处理。
  • 这似乎太长太复杂了..这就是为什么我没有 首先添加它。我相信它可以更容易地完成 方式。
  • 我用WP po​​st time和edit time因为我不知道怎么节省时间 & 该特定时间的日期使用 WP Post Status Transitions 分隔值.

发布 -> 草稿

    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;
            }
          }

草稿 -> 删除

          // 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) How to use WP Post Status Transitions to register exact date & time of post status change (let's name it valueX)?

在我看来,处理这个问题的更好方法不是使用 Post Transition Status Hook ,而是使用 Wordpress Cron - 当管理员更改帖子状态时将调用 Hook 。我们将只使用一个 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) Now I bring other value from my theme options (valueY) - it's either a period (e.g 30 days) or date & time

对于下一部分,我将考虑您有两个主题选项,两个时间段:一个用于名为 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) How to make a calculation with valueX and valueY to get valueZ -> that's date & time when post deletes itself!

这就是乐趣所在。我们将注册一个每小时执行一次的 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); 以显示到期日期。

关于php - 如何使用 WP 帖子状态转换来处理帖子到期日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32052361/

有关php - 如何使用 WP 帖子状态转换来处理帖子到期日期的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  5. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  6. ruby - 在 Ruby 中使用匿名模块 - 2

    假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于

  7. ruby - 使用 ruby​​ 和 savon 的 SOAP 服务 - 2

    我正在尝试使用ruby​​和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我

  8. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  9. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  10. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

随机推荐