Last active
January 19, 2019 17:47
-
-
Save adamcapriola/6729bc5a222124b87cfc1a125b2c2fb9 to your computer and use it in GitHub Desktop.
Attachment source fields (add and save)
This file contains 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 | |
/** | |
* Attachment source fields | |
* @link https://kaspars.net/?p=3203 | |
* @link https://www.billerickson.net/?p=3555 | |
* | |
*/ | |
// Add fields | |
add_filter( 'attachment_fields_to_edit', 'ac_attachment_fields_to_edit_source', 10, 2 ); | |
function ac_attachment_fields_to_edit_source( $form_fields, $post ) { | |
// Source URL | |
$form_fields['source_url'] = array( | |
'label' => esc_attr( 'Source URL' ), | |
'input' => 'url', | |
'value' => esc_url( get_post_meta( $post->ID, '_wp_attachment_source_url', true ) ), | |
); | |
// Source Name | |
$form_fields['source_name'] = array( | |
'label' => esc_attr( 'Source Name' ), | |
'input' => 'text', | |
'value' => esc_attr( get_post_meta( $post->ID, '_wp_attachment_source_name', true ) ), | |
); | |
return $form_fields; | |
} | |
// Save fields | |
add_filter( 'attachment_fields_to_save', 'ac_attachment_fields_to_save_source_url_name', 10, 2 ); | |
function ac_attachment_fields_to_save_source_url_name( $post, $attachment ) { | |
// Source URL | |
if ( isset( $attachment['source_url'] ) ) { | |
// Get previous value | |
$source_url = get_post_meta( $post['ID'], '_wp_attachment_source_url', true ); | |
// If there is a change | |
if ( $source_url !== $attachment['source_url'] ) { | |
// Delete | |
if ( empty( $attachment['source_url'] ) ) { | |
delete_post_meta( $post['ID'], '_wp_attachment_source_url' ); | |
} | |
// Update | |
else { | |
update_post_meta( $post['ID'], '_wp_attachment_source_url', $attachment['source_url'] ); | |
} | |
} | |
} | |
// Source Name | |
if ( isset( $attachment['source_name'] ) ) { | |
// Get previous value | |
$source_name = get_post_meta( $post['ID'], '_wp_attachment_source_name', true ); | |
// If there is a change | |
if ( $source_name !== $attachment['source_name'] ) { | |
// Delete | |
if ( empty( $attachment['source_name'] ) ) { | |
delete_post_meta( $post['ID'], '_wp_attachment_source_name' ); | |
} | |
// Update | |
else { | |
update_post_meta( $post['ID'], '_wp_attachment_source_name', $attachment['source_name'] ); | |
} | |
} | |
} | |
return $post; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment