0

I am looking into the correct way of adding schema.org to the images of all my posts. I am already using a plugin (wpprop) which is adding schema to the header, blogpost, comment section, and other areas, but I particularly want some code to add in the theme for media files in single posts and attachment posts.

I have tried adding itemprop=image in functions.php but this does not work anymore; it is showing an error in the Google structure data tool.

Here is the code, I found it on a WordPress site:

add_filter( 'works_secondary-image_thumbnail_html', 'mediaboxlv_image_itemprop', 10, 3 );
function mediaboxlv_image_itemprop( $html, $post_id, $post_image_id {
    $htmlstr_replace( 'src', ' itemprop="image" src', $html ); 
    return $html;
}
  • Please show us the code which you have tried in your functions.php! – MinhTri Aug 8 '16 at 6:51
0

works_secondary-image_thumbnail_html is not a WordPress core hook, so your code never executes.

As long as images are displayed on your site by calling wp_get_attachment_image in your theme, you can add to the attributes by hooking into wp_get_attachment_image_attributes:

add_filter( 'wp_get_attachment_image_attributes', 'wpse_235266_image_attributes', 10, 3 );

function wpse_235266_image_attributes( $attr, $attachment, $size ) {

    $attr['itemprop'] = 'image';
    return $attr;

}

For images that have been inserted into post content in the visual editor, you'll need to filter on the get_image_tag hook to change the HTML that is inserted into each post.

add_filter( 'get_image_tag', 'wpse_235266_image_html', 10, 6 );

function wpse_235266_image_html( $html, $id, $alt, $title, $align, $size ) {

    return str_replace( '<img ', '<img itemprop="image" ', $html );

}

Note that this means your existing posts, where the HTML is already saved within the content, will not get your new attributes. You'll either need to perform a global replace on old post data to make this change or work through your posts in the editor making changes to all images that cause WP to write the HTML into the post content afresh.

  • thanks for answering.. I am trying to achieve something like this link as you can see there is some kind of link in progress which is producing five sizes of attachment pages on the page, one time with title and alt and rest of the time with alt only using schema attribute, how to do it... right now I am using this code which is working for the gallery images only i want it to work for all the images in the wordpress – sana123 Sep 11 '16 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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