I’m using PHP to dynamically create a custom post, and I need the author to be someone other than the logged in user. I found this https://stackoverflow.com/questions/5759359/wordpress-manually-set-the-author-of-a-post-in-php but I’m wondering if there is a way to do it after the post is already inserted. I guess I could just do a db query…
Leave a Reply
You must be logged in to post a comment.
If you know the ID of the author you can use wp_insert_post specifying the ID and the author ID to it.
The trick is to specify the ID to update the post. See
wp_insert_post()
.For simplicity and relevancy between this question and another question asked on Stack Overflow (wordpress – manually set the author of a post in php — As linked by OP here on WPSE.).
WordPress seems to force a value for the
post_author
while inserting or updating posts usingwp_insert_post()
andwp_update_post()
.The way around it is to use the filter hook
wp_insert_post_data
.Example Usage of filter hook
wp_insert_post_data
:This can be particularly nice for inserting or updating posts using
PHP
.Note: You will want to be sure to disable the support for
author
in your Custom Post Type and probably be cautious using any author related functions within the scope of this Post Type.If this is a custom post type and you don’t want an author assigned to a post you can remove ‘author’ from
supports( array )
in register_post_type. http://codex.wordpress.org/Function_Reference/register_post_typeIf you still need author support for your post type, this would make much more sense to just do this in post.php / post-new.php by filtering the author metabox.
The solution is to add a none or null user to the dropdown using wp_dropdown_users
'show_option_none'
WordPress will use<option value="-1">
for your null user but it will show up as 0 in the db.*Note: This example also moves the author div right above the publish button.
Im sure you notice all the extra conditional checks for $selected. It might be overkill but eliminated any issues with editors not being able to change an author to none from previous published posts.