你应该考虑加入comment_class()
和post_class()
过滤器,如果您的主题支持它。
使用comment_class
过滤器:
我们可以添加以下过滤器:
/**
* 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">
其中
reykjavik
已添加为给定评论作者的城市用户元。
使用post_class
过滤器:
对于
post_class
过滤器,我们可以使用:
/**
* 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 );
下面是一个在循环中工作的较短版本:
/**
* 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">
其中
reykjavik
根据上面的过滤器,已添加为最后一个post类。