In WordPress, I have added a custom field on my posts page called "post-expiry" in which I am enterting an expiry date formatted like this: "2011-04-28".
Each post can have a different expiry date set. Once an expiry date passes, I want to apply a class to my post on the front end called "expired" whic开发者_Go百科h changes the visual style of the post.
Therefore, I need to devise a PHP function to sit within the WordPress Post Loop, that checks the date entered in my custom field meta, checks the actual date (perhaps checking with the web server or an internet time service) and then applies a class to the output if the date has passed.
Does anyone have any ideas about how I would code this function? I am still fairly new to PHP but I think its possible.
I am not sure what the wordpress variable names are (you will need to look that up :p), but here is how to function would look:
<?= time() > strtotime( $post-expiry ) ? 'expired' : '' ?>
strtotime()
turns a string into a unix timestamp, and time()
gets the server time's unix timestamp.
The function can be put right into the class=" "
part of whatever element you want it applied in.
Hope this helps
WordPress allows hooking of the post_class() method, so you could do something purely in your functions.php, say:
// 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');
This should have the advantage of working with any theme, and only needs to be coded in one place.
Also, you could use this alone as the functions.php of a child theme to add the functionality without changing the parent theme.
精彩评论