更改后的代码:
<?php
$post_id = get_the_ID();
$queried_post = get_post($post_id);
$user_info = get_userdata($post->post_author); // <-- or: $user_info = get_the_author_meta(\'ID\')
$first = $user_info->first_name; // what if it is empty or contains forbidden characters?
$last = $user_info->last_name; // as obove
wp_set_post_tags( $post_id, $first, true ); // <-- tag slug, used in the code below
// --- display tag ---
if ( has_tag("$first") )
{
$author_tag = get_term_by( \'slug\', "$first", \'post_tag\' );
if ( $author_tag instanceof WP_term )
{
$a_name = $author_tag->name;
$a_link = get_term_link( $author_tag->term_id );
// display tag
echo \'<a href="\' . esc_url( $a_link ) . \'" rel="tag">\' . $a_name . \'</a> \';
}
}
?>
就我个人而言,我会将代码添加到动作挂钩
save_post_{post_type}
并在以下时间执行
$update
参数为
FALSE (创建了一个新帖子)。
add_action( \'save_post_post\', \'se337414_add_author_tag\', 20, 3 );
function se337414_add_author_tag( $post_id, $post, $update )
{
// create tag only when post is created
if ( $update == true )
return;
$user_info = get_userdata( $post->post_author );
$tag_parts = [];
if ( !empty($user_info->first_name) )
$tag_parts[] = $user_info->first_name;
if ( !empty($user_info->last_name) )
$tag_parts[] = $user_info->last_name;
$tag_slug = implode( \'-\', $tag_parts );
if ( empty($tag_slug) )
return;
wp_set_post_tags( $post_id, $tag_slug, true );
}