Skip to content

Instantly share code, notes, and snippets.

@5ally
Created November 5, 2019 13:45
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 5ally/e5a9b9d97e73810bacf947d819f46fc5 to your computer and use it in GitHub Desktop.
Save 5ally/e5a9b9d97e73810bacf947d819f46fc5 to your computer and use it in GitHub Desktop.
<?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' );
<?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