I am looking into the correct way of adding schema 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;
}
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;
}
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.
functions.php
! – Minh Tri Commented Aug 8, 2016 at 6:51