WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've been doing a lot of research and I've yet to work this out. Can you add in a custom option in the Attachment Display Settings (part of Insert Media dialog in post editor)?

What I'm after is the ability to add an anchor with a class around all images in posts.

share|improve this question
advancedcustomfields.com can do this, when you create a new field group for you extra field, choose the Attachment location and it will display the extra field in the Insert Media dialog and on the attachment edit page too – passatgt Jan 19 '14 at 14:09

This will add a field in the attachment edit screen for applying a class to the img tag.

function IMGattachment_fields($form_fields, $post) {
    $form_fields["imageClass"]["label"] = __("Image Class");
    $form_fields["imageClass"]["value"] = get_post_meta($post->ID, "_imageClass", true);
    return $form_fields;
add_filter("attachment_fields_to_edit", "IMGattachment_fields", null, 2);
function my_image_attachment_fields_save($post, $attachment) {
    if ( isset($attachment['imageClass']) )
    update_post_meta($post['ID'], '_imageClass', $attachment['imageClass']);
    return $post;
add_filter("attachment_fields_to_save", "my_image_attachment_fields_save", null, 2);
share|improve this answer

You just need to add this to your theme's functions.php file:

* Attach a class to linked images' parent anchors
* e.g. a img => a.img img
function give_linked_images_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ) {
    $classes = 'img'; // separated by spaces, e.g. 'img image-link'

    // check if there are already classes assigned to the anchor
    if ( preg_match('/<a.*? class=".*?">/', $html) ) {
    $html = preg_replace('/(<a.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html);
    } else {
     $html = preg_replace('/(<a.*?)>/', '$1 class="' . $classes . '" >', $html);
    return $html;

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.