I would like to set individual facebook open graph meta images (og:image
) for specific posts in Wordpress.
For example, set og:image
to cat_1_image.jpg
if the post is in category 1, and set it to cat_2_image.jpg
if the post is in category with id = 2.
Pseudo-Code:
if($category->term_id == 1)
og:image = 'cat_1_image.jpg';
elseif($category->term_id == 2)
og:image = 'cat_2_image.jpg';
elseif($category->term_id == 3) // CatID 3 means 'Post has images, no default og:image, please'
og:image = '';
Now, I've looked at the various hooks of wpseo, like wpseo_pre_analysis_post_content
and wpseo_opengraph_image
but this does not seem to lead in the right direction.
Can anybody please explain to me how to achieve different og:images for different post categories?!
The reason for my hack: WP SEO does not pick up images which are inserted into a post using the gallery shortcode. It will fall back to include the default image (as specified under WP SEO options) as the og:image. Hence I want to disable the inclusion of the default image for posts of a certain category (i.e. category 'has_images') and let the facebook scraper pick up the gallery images - they DO get picked up if no default og:image is present!
You could try something like this (not tested). It uses the wpseo_opengraph_image
Yoast filter for the opengraph image.
add_filter('wpseo_opengraph_image', 'category_image');
function category_image($image) {
global $post;
if( in_category( 'category1', $post->ID ) ) {
$image = get_stylesheet_directory_uri().'/images/cat_1_image.jpg';
} elseif(in_category( 'category2', $post->ID )) {
$image = get_stylesheet_directory_uri().'/images/cat_2_image.jpg';
}
return $image;
}
In this example i'm guessing your images are in your themes images folder.
Note that the accepted answer provided by Rich only works if your Wordpress theme/functions sets the _thumbnail_id
meta value for the posts. In my case, it doesn't (due to various customisations), so I had to fake that part by adding a filter to get_post_metadata
and returning the correct custom thumbnail_id when the meta data is being fetched:
add_filter('get_post_metadata', 'so28295023', 10, 4);
function so28295023($ignore, $object_id, $meta_key, $single ) {
if($single && $meta_key == '_thumbnail_id') {
return get_custom_thumbnail_id();
}
}
Naturally, get_custom_thumbnail_id()
is my own function which returns the ID of the thumbnail I want attached. I did not find a way to simple return the path of the thumbnail instead of the ID.