【问题标题】:Wordpress - get_the_author_meta() not working when id field is not specifiedWordpress - 未指定 id 字段时 get_the_author_meta() 不起作用
【发布时间】:2021-06-03 06:06:49
【问题描述】:

我试图通过 get_the_author_meta() 函数在我的 single.php 页面上简单地显示帖子作者的姓名和描述,但是当我用数字填充 id 字段时,我只能让它返回一个值什么不理想,因为作者根据帖子而变化。我真的不明白为什么 wordpress 默认没有获取当前帖子作者的 id。有人可以帮我吗?

这是我正在使用的代码

<div class="col-8 col-md-10">
        <?php $id=get_the_author_meta('ID'); echo $id ?>//getting the author's id this way doesn't work
        <h2><?php echo get_the_author_meta('nickname',1);?></h2>//this works but only because I filled the id field with a valid number
        <p><?php echo get_the_author_meta('user_description') ?></p>//this doesn't workalso
    </div>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    设法使用 get_post_field( 'post_author' ) 解决它。我不在循环中,而是在常规帖子中,所以我需要使用此函数来获取作者的 id,然后我设法让其余部分正常工作

    这是代码

    <div class="col-8 col-md-10">
            <?php $id=get_post_field( 'post_author' )?>
            <h2><?php echo get_the_author_meta('first_name',$id).' '.get_the_author_meta('last_name',$id);?></h2>
            <p><?php echo get_the_author_meta('user_description',$id) ?></p>
        </div>
    

    【讨论】:

    • 如果它是你正在查看的帖子的元数据,你可能希望重构一些东西,这样它就在循环内部,但如果这可行,那就太好了!
    【解决方案2】:

    来自the docs on get_the_author_meta()

    如果在The Loop中使用,用户ID不需要指定,默认为当前帖子作者。如果在 The Loop 之外使用,则必须指定用户 ID。

    根据您的分享,如果没有用户 ID,它将无法工作,我怀疑您不在 The Loop 中。没有看到更多你的single.php 模板,很难说,所以如果你能分享更多,那会有所帮助。

    【讨论】:

    • single.php 默认在循环中。
    • @disinfor 这不一定是真的;当您访问单个帖子时,WordPress 将使用single.php,遵循Template Hierarchy for a single Post
    • 正如 OP 在their answer 中提到的那样,它们不在循环中。
    • 我认为我们在争论语义,因为模板层次结构将调用 single.php 你不需要循环,因为 WP 已经在层次结构中调用它。在此处查看关于已接受答案的第一条评论:stackoverflow.com/questions/21249888/…
    • 正如您链接到的答案指出的那样,您仍然需要在循环中。即,您的 single.php 需要包含 while 循环。模板层次结构仅规定 WordPress 加载的 PHP 文件;如果加载的内容没有定义循环,那么你就没有循环!
    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-13
    相关资源
    最近更新 更多