Set Post Parent for Media Set via a Custom Fields [WordPress]
While creating a podcast website I discovered a fantastic plugin by Steve Taylor called Developer’s Custom Fields. I used it to add the podcast as custom fields which allowed me to easily handle the custom placement of the item in the layout while still giving the end-user the convenience of the Media Library to select the audio file.
One issue, however, was that by not having WP insert the podcast in it’s normal fashion, the attachment wasn’t actually linked to the post (ie had the post set as it’s “post_parent”). This resulted in the URLs being of the ugly ?attachment_id=123 variety rather than the friendly version. It also prevented the podcasts from showing up in the feed.
The snippet below sets the post_parent of an attachment. It uses Steve’s plugin API is easily adaptable to other scenarios…
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<code>/** * Set post parent on podcast custom field attachments */ function nf_set_post_parent_for_podcast_custom_fields($post_id, $post) { // Safety check for plugin api function if (!function_exists('slt_cf_field_value')) return ''; // The loop was for when I had multiple fields to attach. It's unnecessary as it stands now... foreach ( array( 'podcast' ) as $key ) { // Get the attachment id stored in the field. if ($attach_id = slt_cf_field_value( $key, 'post', $post_id )) { $attachment = get_post( $attach_id ); $attachment->post_parent = $post_id; wp_update_post( $attachment ); } } } add_action('save_post', 'nf_set_post_parent_for_podcast_custom_fields', 10, 2); </code> |


