A couple of days ago I was trying to add classes to comments using WordPress 2.7+ filter comment_class. I ran into a little confusion which I thought could tie someone up and though I should share it.
To start with here is how it works:
add_filter( “comment_class” , “add_class” , 10 , 4 );
function add_class( $classes, $class, $comment_id, $page_id){
//get the comment object
$_comment = get_comment($comment_id);
//do stuff with comment
//add our new class
$classes[] = “newclass”;
//send the array back
return $classes;
}
This is all simple enough, and works without issue. But it isn’t doing quite what it appears to be doing, and this is where the confusion comes in.
When the filter is actually run it does indeed pass those four variables ($classes, $class, $comment_id, $page_id). However, in the function that calls the filter, and the function that calls that function, the comment_id and page_id are optional. They set themselves to Null if a value isn’t given. When this whole chain begins the comment_id and page_id are not actually passed to any of those functions, so although the filter is sending them, their value is Null.
In the example above that isn’t a problem because get_comment checks to see if the comment_id passed was empty and if so goes off and grabs the comment from a global variable. So it does return the right comment. But if you wanted to use the comment_id or the page_id to grab a value that you have saved somewhere else (in one of your own options, or perhaps you are getting a custom field) this could confuse matters. It won’t work.
So, to sum it all up. If you want the comment_id or the page_id you need to get the comment, as shown above, and then get those values from the comment. You cannot rely on the filter passing those values.