-
-
Save 5ally/e5a9b9d97e73810bacf947d819f46fc5 to your computer and use it in GitHub Desktop.
See https://wordpress.stackexchange.com/q/351867/137402 for details.
This file contains 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 | |
function add_image_link() | |
{ | |
add_meta_box( | |
'image_link_box', | |
'Link image to url', | |
'image_link_field', | |
'attachment' | |
); | |
} | |
add_action( 'add_meta_boxes_attachment', 'add_image_link' ); | |
function image_link_field( $post ) | |
{ | |
?> | |
<label for="image-link">Link URL</label> | |
<input type="text" name="image_link" id="image-link" class="postbox" value="<?php | |
echo esc_attr( get_post_meta( $post->ID, 'image_link_url', true ) ); ?>"> | |
<?php | |
} | |
function save_image_link( $post_id ) | |
{ | |
if ( array_key_exists( 'image_link', $_POST ) ) { | |
update_post_meta( | |
$post_id, | |
'image_link_url', | |
sanitize_text_field( $_POST['image_link'] ) | |
); | |
} | |
} | |
add_action( 'edit_attachment', 'save_image_link' ); |
This file contains 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 | |
// This part adds the custom field to the dialog. | |
add_filter( 'attachment_fields_to_edit', function ( $form_fields, $post ) { | |
$form_fields['image_link'] = [ | |
'label' => 'Link to image URL', | |
'value' => get_post_meta( $post->ID, 'image_link_url', true ), | |
]; | |
return $form_fields; | |
}, 10, 2 ); | |
// This part saves the field as a meta data. | |
add_filter( 'attachment_fields_to_save', function ( $post, $attachment ) { | |
if ( isset( $attachment['image_link'] ) ) { | |
$meta_input = isset( $post['meta_input'] ) ? | |
(array) $post['meta_input'] : []; | |
$meta_input['image_link_url'] = $attachment['image_link']; | |
$post['meta_input'] = $meta_input; | |
} | |
return $post; | |
}, 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment