I need to add the author of a post's name to the post's tags whenever the post is published. So for example John Smith wrote a post, the tag 'John Smith' would be added to that post's tags.

I've tried a couple of different ways, but I think I'm closest with this:

 In functions.php:

 add_action( 'save_post', 'add_authors_name');
 function add_authors_name( $post_id ) {
 $post_author = get_the_author($post_id);
 wp_set_post_terms( $post_id, "$post_author", 'post_tag', true );

This doesn't work, but I think I'm getting there. Just not sure what I'm missing... Could anyone shed some light on this?

  • You can check what wp_set_post_terms() returns -- $ret = wp_set_post_terms( $post_id, $post_author, 'post_tag', true );. If it's boolean false, a string, or a WP_Error object, you've got an error somewhere in your function call. (Also, you shouldn't need to surround $post_author in quotes.) – Pat J May 22 '13 at 14:08
  • Thanks! I surrounded it in quotes as it didn't work when it wasn't. Was just making sure. – nerdarama May 22 '13 at 14:16

Check get_the_author()

(Note:This tag must be used within The Loop.)

you code may be like this In functions.php:

add_action( 'save_post', 'add_authors_name');
 function add_authors_name( $post_id ) {
 global $post;
 $post_author = $post->post_author;  // returns the Author ID
 // get the author's WP_User object so we can get the Author Name
 $post_author_obj = get_userdata( $post_author );
 $post_author_name = $post_author_obj->first_name . ' ' . $post_author_obj->last_name;
 wp_set_post_terms( $post_id, $post_author_name, 'post_tag', true );
  • This is great. Thank you. So close now. It adds a tag, but post_author is the author's ID. Is there a way to change it to the author's name before setting the post terms? I tried get_userdata() but that just broke everything. – nerdarama May 22 '13 at 14:23
  • Okay, thank you Ravs and @Pat J. That worked perfectly. – nerdarama May 22 '13 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.