在文章中显示有限的标签

时间:2019-05-08 作者:rocketsin6

我有一个返回文章所有标记的代码。但这不是我想要的,我只想返回作者姓名作为标记。

<?php the_tags() ?></span> <br />
这将返回分配给文章的所有标签。我该怎么做才能让它只返回作者的名字?

返回帖子中所有标记(包括作者姓名)的默认代码。

<?php 
    $post_id = get_the_ID();
    $queried_post = get_post($post_id);
    $user_info = get_userdata($post->the_author);
    $first = $user_info->last_name;         
    $last = $user_info->last_name;  
    wp_set_post_tags( $post_id, $first, true );     
    if ( has_tag(\'$first-$last\') ) { $author_tag = get_term_by( \'slug\', \'$first-$last\', \'post_tag\' ); 
    echo esc_html( $author_tag->name ); }       
?>

1 个回复
SO网友:nmr

更改后的代码:

<?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 );
}