【问题标题】:Wordpress: Don't manage to retrieve author's name from php functionWordpress:不要设法从 php 函数中检索作者的姓名
【发布时间】:2013-06-28 08:22:37
【问题描述】:

我正在创建一个函数,当帖子发布在我的 WordPress 博客上时,它会向邮件列表发送电子邮件。

function announce_post($post_id){
    $email_address = 'address.of@the-mailing.list';

    $subject = "New Post: " . get_the_title($post_id);
    $body = "Hi,\r\n\r\n" .
        "SOMEONE has just published the article \"" . 
        get_the_title($post_id) . "\" on \"BLOG TITLE\".\r\n\r\n" .     
        "You can read it at " . get_permalink($post_id) . "\r\n" .
        "or visit BLOG_ADDRESS.\r\n\r\n" .
        "Best wishes\r\n" .
        "The Publisher";

    if (wp_mail($email_address, $subject, $body, "From: \"BLOG TITLE\" <address.of@the-blog>")) { }
}

add_action('publish_post','announce_post');

因为它的功能运作良好,但我当然会将SOMEONE 替换为实际帖子的作者姓名。而且我无法找回它。
get_the_author($post_id)get_post_meta($post_id, 'author_name', true) 以及我尝试过但不记得的任何其他方法都不起作用。一切都刚刚返回""

那么在给定帖子 ID 的情况下,检索帖子作者姓名的正确方法是什么?

【问题讨论】:

  • 检查语法高亮,看到了吗?这是你的代码有问题吗,你有语法错误吗?
  • 不,它是在用假人替换博客标题时发生的。
  • 该功能在服务器上运行,现在这里看起来也正常...

标签: php wordpress metadata


【解决方案1】:

get_the_author() 是一个(可能具有误导性)函数,旨在用于the loop。它只是参数is now deprecated。还值得注意的是,作者数据不会存储为帖子元数据,因此任何get_post_meta 尝试都将是徒劳的。

您实际上应该使用get_the_author_meta( 'display_name', $author_id )。我建议接受你的钩子中的第二个参数,即$post 对象,以获取作者 ID:

function announce_post( $post_id, $post ) {
    $name = get_the_author_meta( 'display_name', $post->post_author );
}

add_action( 'publish_post','announce_post', 10, 2 );

【讨论】:

  • 谢谢。我想我自己从来没有通过文档找到这个:-(
猜你喜欢
  • 1970-01-01
  • 2016-12-16
  • 2017-08-09
  • 1970-01-01
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
相关资源
最近更新 更多