Skip to content

Instantly share code, notes, and snippets.

@PatelUtkarsh
Last active August 3, 2019 05:21
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 PatelUtkarsh/bb2270493225a63c74b3ca590b9a4e9c to your computer and use it in GitHub Desktop.
Save PatelUtkarsh/bb2270493225a63c74b3ca590b9a4e9c to your computer and use it in GitHub Desktop.
Attachment custom fields
<?php
namespace Utkarsh\Attachment\Meta;
const META_NAME = 'media_credit';
/**
* Bootstrap.
*/
function bootstrap() {
add_filter( 'attachment_fields_to_edit', __NAMESPACE__ . '\\attachment_custom_fields', 10, 2 );
add_filter( 'attachment_fields_to_save', __NAMESPACE__ . '\\attachment_fields_save', 10, 2 );
}
/**
* Add attachment additional fields.
*
* @param array $form_fields Fields.
* @param WP_Post $post Post object.
*
* @return array modified form fields.
*/
function attachment_custom_fields( array $form_fields, WP_Post $post ): array {
$form_fields[ META_NAME ] = [
'label' => esc_html__( 'Credit', 'domain' ),
'input' => 'text',
'value' => get_post_meta( $post->ID, META_NAME, true ),
];
return $form_fields;
}
/**
* Attachment save custom fields.
*
* @param array $post Post array.
* @param array $attachment Attachment data.
*
* @return array Post array.
*/
function attachment_fields_save( array $post, array $attachment ): array {
if ( isset( $attachment[ META_NAME ] ) ) {
update_post_meta( $post['ID'], META_NAME, sanitize_text_field( $attachment[ META_NAME ] ) );
}
return $post;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment