-
Hello, I am trying to set up a custom featured image (og:image) for every post. I am trying to set up the first image in the post, to achieve this I created this code snippet:
add_filter("rank_math/opengraph/facebook/image", "set_og_image_as_first_image_in_aside");
function set_og_image_as_first_image_in_aside($attachment_url) {
global $post;// Check if it's a single post and has a featured image set
if (is_single() && has_post_thumbnail($post->ID)) {
$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail_image = wp_get_attachment_image_src($thumbnail_id, 'full');if ($thumbnail_image) {
// Get the first image within the <aside> structure
preg_match('/<div class="afxshop-image">\s*<img src="(.*?)"/', $attachment_url, $matches);if (isset($matches[1])) {
$first_image_url = $matches[1];// Use the first image URL as the OpenGraph image
return esc_url($first_image_url);
}
}
}// If no changes, return the original attachment URL
return $attachment_url;
}
I had used the filter of RankMath, as you can see. However, it does not work.
Could you please provide me some clarification in case that I am doing wrong.
Thanks in advance.
The ticket ‘Custom og:image’ is closed to new replies.