【问题标题】:WordPress / PHP - Adding a Class to a Post when a date passesWordPress / PHP - 在日期过去时向帖子添加一个类
【发布时间】:2011-05-23 12:51:53
【问题描述】:

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

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

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

有人对我如何编写这个函数有任何想法吗?我对 PHP 还很陌生,但我认为这是可能的。

【问题讨论】:

    标签: php wordpress class date


    【解决方案1】:

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

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

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

    该函数可以直接放入您想要应用它的任何元素的class=" " 部分。

    希望对你有帮助

    【讨论】:

    • 我会尝试使用此代码作为基础,看看是否可以让它工作
    【解决方案2】:

    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');
    

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

    另外,您可以单独使用它作为child theme 的functions.php 来添加功能而不更改父主题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多