【问题标题】:How to get post author name in WordPress?如何在WordPress中获取帖子作者姓名?
【发布时间】:2017-08-09 20:45:42
【问题描述】:

在 WordPress 中,我需要获取使用 author_id 创建帖子的作者的姓名。
如何找到author_name

【问题讨论】:

标签: php mysql wordpress posts hook-wordpress


【解决方案1】:

对于那些正在寻找关于如何在 WordPress 中获取帖子作者的无缝解决方案的人来说,这是另一种轻量级的方法。

global $wpdb;

    $post_id = 12; // your post id
    
    $post_author_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_author FROM {$wpdb->posts} WHERE ID = %d ", $post_id ) );
    
    $author =  new WP_User( $post_author_id );
    
    $display_name = $author->display_name;
    
    $avartar = get_avatar( $post_author_id, 30 ); // get_avatar( userid, size )
    
    $author_url = get_author_posts_url( $post_author_id );

【讨论】:

    【解决方案2】:

    在 WordPress 自定义 REST API 端点中使用时,您可以这样做:

    function customrestapiplugin_getpost( $slug ) {
        $args = [
            'name' => $slug['slug'],
            'post_type' => 'post'
        ];
    
        $post = get_posts($args);
        
        $data[$i]['id'] = $post[0]->ID;
            $data['title'] = $post[0]->post_title;
            $data['content'] = $post[0]->post_content;
            $data['excerpt'] = $post[0]->post_excerpt;
            $data['slug'] = $post[0]->post_name;
            $data['date'] = $post[0]->post_date;
            $data['link'] = get_permalink($post[0]->ID);
            $data['author'] = get_the_author_meta('display_name', $post[0]->post_author);
            $data['featured_image']['thumbnail'] = get_the_post_thumbnail_url($post[0]->ID, 'thumbnail');
            $data['featured_image']['medium'] = get_the_post_thumbnail_url($post[0]->ID, 'medium');
            $data['featured_image']['large'] = get_the_post_thumbnail_url($post[0]->ID, 'large');
    
        return $data;
    }
    

    【讨论】:

      【解决方案3】:

      在single.php或您想要作者姓名的相关页面中使用以下代码

      <?php get_the_author_meta( 'display_name', $author_id ); ?>
      

      【讨论】:

        【解决方案4】:

        这应该像魅力一样工作

        <?php echo get_the_author(); ?>
        

        更多详细信息。 https://codex.wordpress.org/Function_Reference/get_the_author

        【讨论】:

          【解决方案5】:

          您可以使用get_the_author_meta(),获取作者数据。

          echo get_the_author_meta('display_name', $author_id);
          

          希望这会有所帮助!

          【讨论】:

          • 我发现这个功能被贬低了。
          • @RakhiPrajapati:是吗?我不知道官方文档也没说什么。
          • get_the_author_meta() 不折旧。你可能会想到get_the_author()
          • $author_id的价值从何而来?这令人困惑。
          • @Akshaykn $author_id 指的是属于wp_users.id字段的用户ID。
          【解决方案6】:

          在single-post.php 中添加这段代码

          <?php echo get_the_author(); ?>
          

          我希望这会奏效!

          【讨论】:

          • 上述答案的重复。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-11
          • 1970-01-01
          • 2020-03-16
          • 1970-01-01
          • 2014-05-16
          • 1970-01-01
          相关资源
          最近更新 更多