Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.