我正在创建一个函数,当我的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的情况下,检索帖子作者姓名的正确方法是什么?
答案 0 :(得分:1)
get_the_author()
是一种(可能是误导性的)函数,旨在用于the loop。它只是参数is now deprecated。值得注意的是,作者数据并未存储为post meta,因此任何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 );