Last active
August 29, 2015 13:56
-
-
Save annalinneajohansson/fd6ab2502ef17fe66937 to your computer and use it in GitHub Desktop.
Add custom fields to media upload + append field values to attachment <title>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'attachment_fields_to_edit', 'hip_edit_media_custom_field', 11, 2 ); | |
add_filter( 'attachment_fields_to_save', 'hip_save_media_custom_field', 11, 2 ); | |
function hip_edit_media_custom_field( $form_fields, $post ) { | |
$form_fields['image_source'] = array( | |
'label' => __( 'Bildkälla', 'ds' ), | |
'input' => 'text', | |
'value' => get_post_meta( $post->ID, 'image_source', true ), | |
'show_in_edit' => 1, | |
'show_in_modal' => 1 | |
); | |
$form_fields['photographer'] = array( | |
'label' => __( 'Fotograf', 'ds' ), | |
'input' => 'text', | |
'value' => get_post_meta( $post->ID, 'photographer', true ), | |
'show_in_edit' => 1, | |
'show_in_modal' => 1 | |
); | |
return $form_fields; | |
} | |
function hip_save_media_custom_field( $post, $attachment ) { | |
update_post_meta( $post['ID'], 'image_source', $attachment['image_source'] ); | |
update_post_meta( $post['ID'], 'photographer', $attachment['photographer'] ); | |
return $post; | |
} | |
add_filter( 'wp_get_attachment_image_attributes', 'hip_attachment_attributes', 99, 2 ); | |
function hip_attachment_attributes( $attr, $attachment ) { | |
$attr['title'][0] = $attachment->post_title; | |
$image_source = get_post_meta( $attachment->ID, 'image_source', true ); | |
$photographer = get_post_meta( $attachment->ID, 'photographer', true ); | |
$attr['title'][1] = ( $image_source ) ? sprintf( __( 'Bildkälla: %s', 'ds' ), $image_source ) : "none"; | |
$attr['title'][2] = ( $photographer ) ? sprintf( __( 'Fotograf: %s', 'ds' ), $photographer ) : "none"; | |
$i = 0; | |
foreach ( $attr['title'] as $item ){ | |
if( $item == "none" ) { | |
unset( $attr['title'][$i] ); | |
} | |
++$i; | |
} | |
$attr['title'] = implode( " | ", $attr['title'] ); | |
return $attr; | |
} | |
add_filter( 'image_send_to_editor', 'hip_image_send_to_editor_add_data', 999, 8 ); | |
function hip_image_send_to_editor_add_data( $html, $id, $caption, $title, $align, $url, $size, $alt ) { | |
$html = wp_get_attachment_image( $id, $size, false, array( 'class' => 'rounded' ) ); | |
return $html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment