Pretend you need a block to be visible on a node depending on the value of a date field on the node.
A good example is a website that lists classes as nodes. You want a block visible only on class nodes. You also only want that block visible if the date of the class is in the future.
The classes are created by making nodes of a custom content type called "class". Each class node contains an date field called "class_date" that contains the date of the first day of the class. The date field is a regular ISO date field type. This PHP snippet returns TRUE if the node is a "class" and the "class_date" field is in the future and the block is then visible.
<?php
$node = menu_get_object();
if ( !empty($node) && $node->type == 'class' ) {
if ( !empty($node->field_class_date) && !empty($node->field_class_date['und']) && !empty($node->field_class_date['und'][0]) ) {
$parts = explode('T', $node->field_class_date['und'][0]['value']);
$date_parts = explode('-', $parts[0]);
$class_date = $date_parts[1] . '/' . $date_parts[2] . '/' . $date_parts[0] . ' ' . $parts[1];
$on = strtotime($class_date);
$now = time();
if ( $on >= $now ) {
return TRUE;
}
}
}
return FALSE;
?>
Thanks to Nevets for the help.
Comments
Think there is a logic error in this snippet
Greetings,
I could be wrong, since I am a noob at PHP, but I think the snippet should read :
[...]
if ( $on < $now ) {
return TRUE;
[...]
$on represents the Date field and you want the block to show up if it is less than the current time ($now).
Michael Lessard
webmaster of Quebec City "democracy in action" media
This snippet does not work for me with Date 7.x
With Date module 7.x, this snippet does not work. No errors as such, but the block does not consider this date filter snippet.
NODE TYPE : evenement [the word event in French]
FIELD : field_date
I tried this ...
I presume this snippet is not adapted for Date 7.x and it also looks more complicated than it should be. I personally just need it to be true if the event year is not the current year.
Michael Lessard
webmaster of Quebec City "democracy in action" media