Replace Yoast og:image in single custom post type

I'm trying to replace the custom yoast og:image in a specific post type to use a custom meta field instead of the featured image. What I got so far is:

function my_wpseo_opengraph()
{
  global $post;
  if (is_singular('job_listing')) {
    $og_image = get_post_meta($post-ID, 'pp_job_header_bg', TRUE);
    if (!empty ($og_image)) {

      $GLOBALS['wpseo_og']-image($og_image);
    }
  }
}

add_action('wpseo_opengraph', 'my_wpseo_opengraph', 29);

However, while viewing the source code, it seems that the code won't replace the default og:image, it adds a second og:image.

How do I replace it?

Topic plugin-wp-seo-yoast plugins Wordpress

Category Web


This happens because add_action do not override previos actions, just "adds" to them. You will most likely need to search in the plugin's code to find how it hooks its own og:image output. If it is not hardcoded but uses the same action, you will just need to call remove_action with the same parameters as those it was registers with.

The gotcha is that you have to do it at a point in the execution flow which is after the plugin had already before the action is "run" (duh). IIRC the code below should work for that (but I personally dislike doing things this way, as essentially you are modifying a list while iterating it which is not the most robust idea even if it works)

add_action('wpseo_opengraph', function () { remove_action('wpseo_opengraph'...) }, 0);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.