Blog

  • Adding Custom Field to Media Attachment

    Posted at 04 Jul, 2018 in Tutorials

    You might need to add some CSS class to an image that will change with the image and here is the solution for achieving that. In short, we are going to learn how to add a custom field to the Media attachment.

    Step 1:

    Paste the following code in your theme’s ‘functions.php’. This will add a textarea named ‘Style’ to your Media attachment.

    /** function to add custom media field */
    function custom_media_add_media_custom_field( $form_fields, $post ) {
    $field_value = get_post_meta( $post->ID, 'custom_media_style', true );
    $form_fields['custom_media_style'] = array(
    'value' => $field_value ? $field_value : '',
    'label' => __( 'Style' ),
    'helps' => __( 'Enter your style' ),
    'input' => 'textarea'
    );
    return $form_fields;
    }
    add_filter( 'attachment_fields_to_edit', 'custom_media_add_media_custom_field', null, 2 );

    Here, ‘custom_media_style‘ is the custom field name (which you can use to fetch the data) and in label and helps you can provide the label and description about your custom field.

    /** save your custom media field */
    function custom_media_save_attachment( $attachment_id ) {
    if ( isset( $_REQUEST['attachments'][ $attachment_id ]['custom_media_style'] ) ) {
    $custom_media_style = $_REQUEST['attachments'][ $attachment_id ]['custom_media_style'];
    update_post_meta( $attachment_id, 'custom_media_style', $custom_media_style );
    }
    }
    add_action( 'edit_attachment', 'custom_media_save_attachment' );

    Please note that you need to use the same custom field name (custom_media_style) you used before.

    Step 2:

    Now its time to save the new custom field you added in the previous step. Its too very easy – just add these again in your theme’s ‘functions.php’. Now your new custom field will be shown on the Media attachment popups and you can enter what you want.

    Step 3:

    Now its time to learn how to display our custom field in the theme. Its too quite easy, just use the following function which will print the data.

    $custom_media_style = get_post_meta( , 'custom_media_style', true ));
    echo $custom_media_style;

    That’s it and now you can add any number of custom fields to the Media attachment and manage them easily.

Categories

Categories

Archives

Archives