Support

Account

Home Forums General Issues Add body_class if post has expired

Solved

Add body_class if post has expired

  • I have a custom field where I can set expiry dates for posts.

    What I want to do is to add a body class to posts that have expired but I am stuck.

    I am thinking something along the lines of:

    function add_acf_body_class($class) {
    $expired = get_field('expiry_date', false, false);
    $today = date('F j, Y');
    	if($expired < $today) {
    		$class[] = expired;
    		return $class;
    	}
    }
    add_filter('body_class', 'add_acf_body_class');

    It’s adding the body class but it’s being added to all posts instead of posts that have expired.

  • 
    function add_acf_body_class($class) {
      global $post;
      if (empty($post) || !is_a($post, 'WP_Post')) {
        return $class;
      }
      $expired = get_field('expiry_date', $post->ID, false);
      if ($expired) {
        $today = date('Ymd');
        if($expired < $today) {
          $class[] = 'expired';
        }
      }
      return $class;
    }
    add_filter('body_class', 'add_acf_body_class');
    
  • Thank you, John. Much Apriciated.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Add body_class if post has expired’ is closed to new replies.