Skip to content

Instantly share code, notes, and snippets.

@adamcapriola
Last active January 19, 2019 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcapriola/6729bc5a222124b87cfc1a125b2c2fb9 to your computer and use it in GitHub Desktop.
Save adamcapriola/6729bc5a222124b87cfc1a125b2c2fb9 to your computer and use it in GitHub Desktop.
Attachment source fields (add and save)
<?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