Last active
March 6, 2025 13:51
-
-
Save PatelUtkarsh/bb2270493225a63c74b3ca590b9a4e9c to your computer and use it in GitHub Desktop.
Attachment custom fields
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 | |
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