![]()
A single manually selected social image rarely fits every post, product group, or campaign. You can change the Open Graph Image automatically by defining a reusable PHP resolver, then connecting it to the filter for your active SEO plugin. This guide shows the Yoast SEO and Rank Math integrations separately, so your custom rules stay in one place while the plugin-specific code remains small.
The examples change the Facebook-style Open Graph image; Twitter card images may use separate plugin filters. The safe workflow is to decide how images are chosen, add the code in a site-specific plugin or child theme, and verify the final page tags and image URL. A defined fallback helps ensure posts with missing or invalid custom data still have a suitable Open Graph Image.
Before You Start: Confirm the Plugin and Image Source
Before adding a filter, confirm which SEO plugin currently generates the page metadata. Yoast SEO and Rank Math provide separate integrations; use only the adapter for the active plugin. Enabling both can make debugging harder and may contribute to duplicate metadata if another component also outputs Open Graph tags.
Choose a durable home for the code, such as a site-specific plugin or a child theme. Do not edit a parent theme or an SEO plugin file, because updates can overwrite those changes. Before moving on, pin down the exact source for the image rule and decide what should happen when that source is empty or invalid.
- WordPress 6.4 or later and PHP 8.0 or later, with a current Yoast SEO or Rank Math installation.
- A staging site or a recent backup that you can restore before testing PHP changes.
- Access to a site-specific plugin or child theme where you can maintain the code safely.
- A known rule source, such as an attachment ID in post meta, a taxonomy term, or a per-post fallback.
- At least one suitable Media Library image and permission to inspect the rendered page source.
- A social metadata preview tool or crawler debugger for checking the live URL after deployment.
Prefer storing Media Library attachment IDs rather than copied file paths. WordPress can validate the attachment and generate a suitable image URL, while a deleted or mistyped ID can be handled through the fallback. Also make sure the chosen image is publicly accessible; a URL that only works for logged-in editors will not be available to social crawlers.
Define the Selection Rule and Fallback Open Graph Image
Write down the priority order before connecting the logic to an SEO plugin. A predictable rule makes it easier to test edge cases and prevents different callbacks from choosing different images. For a post, a practical sequence is:
- Use a valid custom attachment ID saved for the post.
- If none is available, use a valid campaign image assigned to the relevant taxonomy term.
- Otherwise, use the post featured image, then a configured site-default attachment as the final fallback.
Store attachment IDs in post meta or term meta where possible, rather than copying image URLs. WordPress can check that an ID belongs to an image and generate the requested size. If a value is empty, malformed, or points to a deleted attachment, continue down the priority list instead of treating it as a valid selection.
Define behavior for requests without a singular post as well. Do not assume a global post is available: use a queried term image only when your rules explicitly support taxonomy archives; otherwise, choose the site default or return an empty string for the plugin to handle. The resolver should return a usable image URL, not an attachment ID or printed markup.
For Developers
Build the Shared Image Resolver
The resolver accepts a post ID (or uses the current queried object) and returns an absolute image URL. It owns the priority rules, validates each Media Library attachment, and returns an empty string if no configured image is usable. Both plugin adapters can call this same function, keeping selection behavior consistent.
Resolve a Valid Attachment URL
This example checks post meta first, then a category campaign image, the featured image, and finally a configured default. The category branch expects term meta named pnet_og_image_id; change the taxonomy or metadata keys to match your setup.
<?php
// Set PNET_DEFAULT_OG_IMAGE_ID to a Media Library attachment ID in site configuration.
function pnet_valid_og_image_url($attachment_id) {
$attachment_id = absint($attachment_id);
if (!$attachment_id || !wp_attachment_is_image($attachment_id)) {
return '';
}
$url = wp_get_attachment_image_url($attachment_id, 'large');
if (!$url) {
$url = wp_get_attachment_image_url($attachment_id, 'full');
}
return $url ? esc_url_raw($url) : '';
}
function pnet_resolve_open_graph_image_url($post_id = 0) {
$post_id = absint($post_id);
if (!$post_id) {
$post_id = absint(get_queried_object_id());
}
$post = $post_id ? get_post($post_id) : null;
if ($post instanceof WP_Post) {
$url = pnet_valid_og_image_url(
get_post_meta($post_id, 'pnet_og_image_id', true)
);
if ($url) {
return $url;
}
$terms = get_the_terms($post_id, 'category');
if (is_array($terms)) {
foreach ($terms as $term) {
$url = pnet_valid_og_image_url(
get_term_meta($term->term_id, 'pnet_og_image_id', true)
);
if ($url) {
return $url;
}
}
}
$url = pnet_valid_og_image_url(get_post_thumbnail_id($post_id));
if ($url) {
return $url;
}
}
if (defined('PNET_DEFAULT_OG_IMAGE_ID')) {
return pnet_valid_og_image_url(PNET_DEFAULT_OG_IMAGE_ID);
}
return '';
}
Store attachment IDs rather than file paths: WordPress validates image attachments and generates the requested size without assumptions about the uploads directory. The helper tries the large size, then full, and rejects missing or non-image attachments. For custom post types, replace category with the taxonomy that holds your campaign image. The WordPress function reference explains the URL-generation API used here.

Resolve a Valid Attachment URL
Use a resolver that checks the post-specific attachment first, then a category campaign image, the featured image, and finally a configured site default. Each candidate is validated as an image before WordPress generates its URL. The function returns a URL string or an empty string; it never prints markup.
<?php
function pnet_valid_og_image_url($attachment_id) {
$attachment_id = absint($attachment_id);
if (!$attachment_id || !wp_attachment_is_image($attachment_id)) {
return '';
}
$url = wp_get_attachment_image_url($attachment_id, 'large');
if (!$url) {
$url = wp_get_attachment_image_url($attachment_id, 'full');
}
return $url ? esc_url_raw($url) : '';
}
function pnet_resolve_open_graph_image_url($post_id = 0) {
$post_id = absint($post_id);
if (!$post_id) {
$post_id = absint(get_queried_object_id());
}
$post = $post_id ? get_post($post_id) : null;
if ($post instanceof WP_Post) {
$url = pnet_valid_og_image_url(
get_post_meta($post_id, 'pnet_og_image_id', true)
);
if ($url) {
return $url;
}
$terms = get_the_terms($post_id, 'category');
if (is_array($terms)) {
foreach ($terms as $term) {
$url = pnet_valid_og_image_url(
get_term_meta($term->term_id, 'pnet_og_image_id', true)
);
if ($url) {
return $url;
}
}
}
$url = pnet_valid_og_image_url(get_post_thumbnail_id($post_id));
if ($url) {
return $url;
}
}
if (defined('PNET_DEFAULT_OG_IMAGE_ID')) {
return pnet_valid_og_image_url(PNET_DEFAULT_OG_IMAGE_ID);
}
return '';
}
Change pnet_og_image_id or category to match your metadata and taxonomy. Define PNET_DEFAULT_OG_IMAGE_ID as a Media Library attachment ID if you want a site-wide fallback. The large size is tried first, with full as a fallback; WordPress handles the URL rather than relying on a hard-coded uploads path.

Did you know: You can explore our complete guide on Customize Yoast Breadcrumbs for step-by-step details.
Connect the Resolver to Yoast SEO
Yoast SEO exposes the wpseo_opengraph_image filter for changing the image URL it uses in its Open Graph output. Add a small adapter that calls the shared resolver from the previous step, then returns the resolver result when one is available. If the resolver returns an empty string, this example keeps Yoast SEO’s existing image rather than removing it.
Add the callback to the same site-specific plugin or child theme that contains the resolver. The example applies the rule to posts and WooCommerce products; edit the allowed post types to suit your site, or remove the condition if the rule should apply to every supported page.
[code lang='php']
The callback adapts the existing selection logic to Yoast SEO’s filter; it does not duplicate the attachment checks or business rules. Keep the resolver loaded before this registration, and confirm Yoast SEO is the plugin generating metadata for the page. If Rank Math generates your metadata instead, use its separate adapter in the following step and do not register both integrations together.
Connect the Resolver to Rank Math
Rank Math provides the rank_math/opengraph/facebook/image filter for changing the image URL used in its Facebook-style Open Graph metadata. Connect the shared resolver with a small adapter: it passes the current post ID to your existing selection logic and returns the selected URL when one is available.
Add this code in the same site-specific plugin or child theme as the resolver, after that resolver has been loaded. The example limits the change to posts and products; adjust the post types to match your rules. If Yoast SEO generates metadata for this page, use the Yoast adapter instead of registering this Rank Math adapter.
[code lang='php']
When the resolver finds no usable image, the callback preserves Rank Math’s existing value instead of replacing it with an empty string. Enable only the adapter for the SEO plugin that outputs metadata on the page; using both adapters is unnecessary and can complicate diagnosis. If your site also customizes Twitter card images, check and implement the corresponding Twitter-specific integration separately, since this filter targets Facebook/Open Graph output.
You might also like:
Verify the Rendered Open Graph Tags
Inspect the published page source or response HTML, not just the SEO editor preview. Find the og:image meta tag and confirm its content value matches the selected image URL. Check that the intended SEO plugin outputs the metadata and that another plugin or theme is not adding a competing set of tags.
Test a page for each rule branch: a valid custom attachment, an empty custom value, an invalid or deleted attachment, and the final fallback. Open each resulting URL in a private browser window. It should be absolute, publicly accessible without a login, return a successful response, and serve an image content type. WordPress documents the attachment URL function used by the resolver in its wp_get_attachment_image_url reference.

When the source is correct but a social platform still shows an old image, purge page, server, and CDN caches, then request a fresh scrape in the platform debugger. Crawler caches can outlive your code change. Once the rendered tag and fetched file both match the expected result, the Open Graph Image rule is verified.
Common Errors
If the selected image does not appear, diagnose the rendered page and the resolver separately. These checks cover the failures most often caused by plugin filters, invalid attachment data, or stale caches.
- The default image still appears: Confirm the active SEO plugin matches the adapter you registered, the callback is loaded, and the filter name is correct. Check that the page meets the callback condition, such as being a singular post or product.
- No image is emitted: Inspect the resolver result and each candidate attachment ID. Confirm the ID belongs to an image and that WordPress can generate the requested size. Review early returns and the final fallback path.
- The wrong post image appears: Do not rely on stale global post context, especially on archives or other non-singular requests. Pass the queried object ID explicitly and verify the request type before resolving an image.
- Duplicate image tags appear: Check for a second SEO plugin, theme metadata, or custom callback emitting Open Graph tags. Remove the competing source rather than adding another filter.
- The preview is stale: If page source has the expected URL, purge page and CDN caches, then refresh the social platform crawler cache. Confirm the URL is absolute and publicly fetchable.
- The filter output is invalid: Return a URL string, not an attachment ID or printed markup. Relative URLs may also fail for social crawlers.
Backup Required
You might also like:
Conclusion
A reliable implementation separates image-selection rules from SEO-plugin integration. Keep one reusable, validated pnet_ resolver responsible for checking attachment IDs, trying the intended priority order, and returning a usable image URL. Then connect it with the small adapter for the plugin that actually generates metadata on your site: Yoast SEO or Rank Math.
Before deploying, run through this checklist on staging and then verify the live page:
- Confirm the fallback is defined for missing, deleted, or invalid custom image values.
- Check that each candidate is a real image attachment and that the resolver returns a URL, not an attachment ID or markup.
- Enable only the adapter for the active SEO plugin, and confirm the callback applies to the intended post types.
- Test a valid custom image, an empty value, an invalid attachment, and each fallback branch.
- Inspect the rendered page source for the expected
og:imageURL, then make sure the image loads publicly.
If the HTML is correct but a social preview remains unchanged, clear relevant page and CDN caches and request a fresh scrape from the platform crawler. Judge the result by the rendered metadata and fetched image, not solely by an editor preview. With the rules tested and the correct adapter active, your Open Graph Image can follow post, taxonomy, or campaign logic while retaining a dependable fallback.