WordPress edit <img> markup to include data attribute

I have a custom field added to the WordPress media uploader, that stores a Vimeo ID. I need to pull this custom field data (if it has been input) into the markup of the default <img> tag in WordPress – I’d like it to be added as a data- attribute.

Having searched around online I have no leads of what to try here, does anybody have any experience with this?

Read More

If the above data- attribute is present, I’d also like to automatically add the class ‘video-thumb’ to that image.

I am able to call the cusotm field as follows, but have no idea how to incorporate this into the <img> tag:

$video_url = get_post_meta($id, 'video-url', true);

Default WordPress <img> code

<img class="aligncenter size-large wp-image-114" src="#" alt="" width="1024" height="435" />

Desired Outcome

<img class="video-thumb aligncenter size-large wp-image-114" src="#" alt="" width="1024" height="435" data-vimeo-id="69171201" />

Related posts

1 comment

  1. You can try this Within your post loop

    $key = 'your custom meta key'

    echo get_post_meta($post->ID, $key, true);

    Full implementation

    <?php
    $query = new WP_Query('showposts=3');
    if ($query->have_posts()):
        while ($query->have_posts()):
            $query->the_post();
            $vimeo = get_post_meta($post->ID, 'your_key', true);
            the_title();
    ?>
    
    <img class="video-thumb aligncenter size-large wp-image-114" src="#" alt="" width="1024" height="435" data-vimeo-id="<?php echo $vimeo; ?>" />
    
    <?php
        endwhile;
    endif;
    wp_reset_query();
    ?>
    

    Please read for more information from here

Comments are closed.