这不是怎么用的add_filter
. 通常,您可以使用它将自定义函数附加到某些WP(或插件或主题)过滤器挂钩。然后在自定义函数中进行处理,并让它返回原始挂钩所需的结果类型。
下面是一个如何使用的示例pre_get_avatar
提前检查自定义头像。如果未找到,get_avatar
, 在嵌套过滤器的位置,继续执行其常规例程以获取Gravatar图像。这个get_avatar
过滤器挂钩在pre_get_avatar
.
add_filter(\'pre_get_avatar\', \'my_pre_get_avatar_filter\', 10, 3);
function my_pre_get_avatar_filter( $avatar, $id_or_email, $args ) {
$user_id = 0;
// Can we get an user ID?
if ( is_int( $id_or_email ) ) {
$user_id = $id_or_email;
} else if ( is_email( $id_or_email ) ) {
$user = get_user_by( \'email\', $id_or_email );
if ( $user ) {
$user_id = $user->ID;
}
} else if ( is_a( $id_or_email, \'WP_User\' ) ) {
$user_id = $id_or_email->ID;
} else {
return $avatar;
}
// If not, bail
if ( ! $user_id ) {
return $avatar; // by default this is null
}
// Check for custom avatar
$custom_avatar = get_user_meta( $user_id, \'wp_user_avatar\' );
if ( is_numeric( $custom_avatar ) && $custom_avatar ) {
// Here you could just get the attachment url and format the img html yourself to include any available $args
$custom_avatar = wp_get_attachment_image($custom_avatar, \'thumbnail\');
// Return custom avatar if image exists
if ( $custom_avatar ) {
// this short circuits get_avatar and prevents it from continuing with the default process of checking for Gravatar image, which would be unnecessary as we already have an avatar image
return $custom_avatar;
}
}
// Return default
return $avatar;
}