You should consider hooking into the comment_class()
and post_class()
filters, if your theme supports it.
Using the comment_class
filter:
We can add the following filter:
/**
* Add a custom comment class, based on a given comment author's user meta field.
*
* @see http://wordpress.stackexchange.com/a/170443/26350
*/
add_filter( 'comment_class', function( $classes, $class, $comment_id, $post_id ) {
// Custom user meta key:
$key = 'city'; // <-- Edit this to your needs!
// Fetch the comment object:
$comment = get_comment( $comment_id );
// Check if the comment author is a registered user:
if ( ! is_null( $comment ) && $comment->user_id > 0 )
{
// Check for the custom user meta:
if( '' !== ( $value = get_user_meta( $comment->user_id, $key, true ) ) )
$classes[] = sanitize_html_class( $value );
}
return $classes;
}, 10, 4 );
Output example:
<li class="comment byuser comment-author-someuser bypostauthor
odd alt depth-2 reykjavik" id="li-comment-78">
<article id="comment-78" class="comment">
where the reykjavik
has been added as the city user-meta, for the given comment author.
Using the post_class
filter:
Similarly for the post_class
filter, we can use:
/**
* Add a custom post class, based on a given post author's user meta field.
*
* @see http://wordpress.stackexchange.com/a/170443/26350
*/
add_filter( 'post_class', function( $classes, $class, $post_id ) {
// Custom user meta key:
$key = 'city'; // <-- Edit this to your needs!
// Fetch the comment object:
$post = get_post( $post_id );
if( ! is_null( $post ) && $post->post_author > 0 )
{
// Check for the custom user meta:
if( '' !== ( $value = get_user_meta( $post->post_author, $key, true ) ) )
$classes[] = sanitize_html_class( $value );
}
return $classes;
}, 10, 3 );
Here’s a shorter version that works within the loop:
/**
* Add a custom post class, based on a given post author's user meta field.
*
* @see http://wordpress.stackexchange.com/a/170443/26350
*/
add_filter( 'post_class', function( $classes, $class, $post_id ) {
// Custom user meta key:
$key = 'city'; // <-- Edit this to your needs!
// Check for the custom user meta:
if( '' !== ( $value = get_the_author_meta( $key ) ) )
$classes[] = sanitize_html_class( $value );
return $classes;
});
Output example:
<article id="post-1"
class="post-1 post type-post status-publish format-standard
hentry category-uncategorized reykjavik">
where the reykjavik
has been added as the last post class, based on our filter above.