Skip to content

Instantly share code, notes, and snippets.

@keesiemeijer
Last active November 16, 2015 16:23
Show Gist options
  • Select an option

  • Save keesiemeijer/65335bccf813442cca4e to your computer and use it in GitHub Desktop.

Select an option

Save keesiemeijer/65335bccf813442cca4e to your computer and use it in GitHub Desktop.
Easy way to have text linking to images
<?php
add_filter( 'attachment_fields_to_edit', 'km_attachment_text_link_field', 10, 2 );
function km_attachment_text_link_field( $form_fields, $post ) {
$form_fields['km-text-link'] = array(
'label' => 'Text Link',
'input' => 'text',
'value' => '',
'helps' => 'If Text Link is provided, the image will be linked from a text link',
);
return $form_fields;
}
add_filter( 'attachment_fields_to_save', 'km_attachment_field_save', 10, 2 );
function km_attachment_field_save( $post, $attachment ) {
if ( isset( $attachment['km-text-link'] ) ) {
update_post_meta( $post['ID'], 'km-text-link', $attachment['km-text-link'] );
} else {
delete_post_meta( $post['ID'], 'km-text-link' );
}
return $post;
}
add_filter( 'image_send_to_editor', 'km_image_text_links_format', 10, 8 );
function km_image_text_links_format( $html, $id, $caption, $title, $align, $url, $size, $alt ) {
$text = get_post_meta( $id, 'km-text-link', true );
if ( !empty( $text ) ) {
list( $img_src, $width, $height ) = image_downsize( $id, $size );
$html = '<a href="' . esc_url( $img_src ) . "\">$text</a>";
}
delete_post_meta( $id, 'km-text-link' );
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment