• How does one add a data reference into a featured image?

    Using the standard WP way:

    the_post_thumbnail( 'thumb', array( 'class' => 'img-responsive' ) );

    and would like to include a data attribute:

    <img src=”example.jpg” data-reference >

    This doesn’t seem to be a standard WP attribute and I’m not sure how to extend the post_thumbnail function (if you can).

    I tried to use an example on this page added by @BarbaraFord – which looks sound, I figured I could shoehorn the data attribute into that. Frustratingly, the above code verbatim does not work. The featured image disappears entirely.

    Is this this the best method to add the data reference to the_post_thumbnail? If so, what’s stopping the below code working?

    https://developer.wordpress.org/reference/functions/the_post_thumbnail/

    /**
     * Link all post thumbnails to the post permalink.
     *
     * @param string $html          Post thumbnail HTML.
     * @param int    $post_id       Post ID.
     * @param int    $post_image_id Post image ID.
     * @return string Filtered post image HTML.
     */
    function wpdocs_post_image_html( $html, $post_id, $post_image_id ) {
        $html = '<a href="' . get_permalink( $post_id ) . '" alt="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
        return $html;
    }
    add_filter( 'post_thumbnail_html', 'wpdocs_post_image_html', 10, 3 );
Viewing 1 replies (of 1 total)
  • You can add the extra data attributes to the array as follows.

    the_post_thumbnail( 'thumb', array(
       'class' => 'img-responsive',
       'data-reference' => '',
       'data-index' => 1,
    ) );

    The above will yield the HTML code below:
    <img src="test.jpg" class="img-responsive" data-reference data-index="1">

Viewing 1 replies (of 1 total)

The topic ‘Adding data attribute to featured image’ is closed to new replies.