I have multiple author accounts on one of my WordPress installs. Often I will create a post, and set the author to be a different account. However, when I upload images into that post, their attachment page lists the author as my account. How can I set the author for posts, and have it carry over to the media associated with that post?
2 Answers
Use this in your theme's functions.php
:
add_filter( 'add_attachment', 'wpse_55801_attachment_author' );
function wpse_55801_attachment_author( $attachment_ID )
{
$attach = get_post( $attachment_ID );
$parent = get_post( $attach->post_parent );
$the_post = array();
$the_post['ID'] = $attachment_ID;
$the_post['post_author'] = $parent->post_author;
wp_update_post( $the_post );
}
-
Thanks! Will this only work for new posts? I added the filter to my
functions.php
but it seems that it won't be applied to existing posts / attachments. Is there a way to do that?– RyanCommented Jun 25, 2012 at 18:42 -
Actually, after adding, it doesn't seem to be working on new posts either.– RyanCommented Jun 25, 2012 at 18:48
-
1@Ryan . Well, I did test before publishing... Re-tested now with WP 3.4 & TwentyEleven 1.4 & Custom Post Type, and another with WP 3.1 & TwentyTen 1.2 & normal Post... Works on both... Can you test in a clean WP install? :::: For updating old posts, couple one of these solutions with my code. Commented Jun 25, 2012 at 20:58
I extended the above solution of @brasofilo to also change the attachment post date to the date of the post parent.
And not only on upload of the attachment, but also when an attachment is edited. You can use the edit_attachment
filter with the same function for this. However, when you do that, the wp_update_post
function causes an infinite loop and leads to PHP memory errors, I found out the hard way after a lot of searching.
A warning for this infinite loop is actually mentioned in the Codex.
A solution is to remove the filters, like so:
function wpse_55801_attachment_author( $attachment_ID ) {
remove_filter('add_attachment', 'wpse_55801_attachment_author');
remove_filter('edit_attachment', 'wpse_55801_attachment_author');
$attach = get_post( $attachment_ID );
$parent = get_post( $attach->post_parent );
$the_post = array();
$the_post['ID'] = $attachment_ID;
$the_post['post_author'] = $parent->post_author;
$the_post['post_date'] = $parent->post_date;
wp_update_post( $the_post );
add_filter( 'add_attachment', 'wpse_55801_attachment_author' );
add_filter( 'edit_attachment', 'wpse_55801_attachment_author' );
}
add_filter( 'add_attachment', 'wpse_55801_attachment_author' );
add_filter( 'edit_attachment', 'wpse_55801_attachment_author' );