WordPress/PHP-当一个日期过去时,在帖子中添加一个类


WordPress / PHP - Adding a Class to a Post when a date passes

在WordPress中,我在我的帖子页面上添加了一个名为"帖子过期"的自定义字段,我在其中输入了一个格式如下的过期日期:"2011-04-28"。

每个帖子都可以设置不同的截止日期。一旦过期,我想在我的帖子前端应用一个名为"过期"的类,它会改变帖子的视觉风格。

因此,我需要设计一个PHP函数来位于WordPress Post循环中,它检查在我的自定义字段元中输入的日期,检查实际日期(可能与网络服务器或互联网时间服务进行检查),然后在日期过去时将一个类应用于输出。

有人知道我该如何编码这个函数吗?我对PHP还是相当陌生的,但我认为这是可能的。

我不确定wordpress变量名是什么(你需要查找:p),但下面是函数的外观:

<?= time() > strtotime( $post-expiry ) ? 'expired' : '' ?>

strtotime()将字符串转换为unix时间戳,time()获取服务器时间的unix时间戳。

该函数可以直接放入任何元素的class=" "部分。

希望这能帮助

WordPress允许挂接post_class()方法,因此您可以纯粹在functions.php中做一些事情,比如:

// Add a class to post_class if expiry date has passed.
function check_expiry_date( $class = '' ) {
  $custom_fields = get_post_custom_values('post-expiry');
  if ($custom_fields) {
    // There can be multiple custom fields with the same name. We'll
    // just get the first one using reset() and turn it into a time.
    $expiry_date = strtotime(reset($custom_fields));
    if ($expiry_date && $expiry_date < time()) {
      if (!is_array($class)) {
        // We were passed a string of classes, so I'll turn that into an array
        // and add ours onto the end. The preg_split is what WP's get_post_class() 
        // uses to split, so I nicked it :)
        $class = preg_split('#'s+#', $class);
      }
      // Now we know we've got an array, we can just add our new class to the end.
      $class[] = 'expired';
    }
  }
  return $class;
}
add_filter('post_class', 'check_expiry_date');

这应该具有处理任何主题的优势,并且只需要在一个地方进行编码。

此外,您可以将其单独用作子主题的functions.php,以在不更改父主题的情况下添加功能。