Search code examples
wordpresswordpress-plugin-creation

add_action(updated_postmeta) to run update_post_meta -> loop


I have an add_action that triggers on a postmeta table change. When triggered, I need to update the post_meta table with the function update_post_meta().

As you can expect, this results in a loop, continuously updating the post meta table.

Does anyone know how to break the loop in this case and run only once?

function seoHomepageTitle() {
  $page = get_page_by_title("Homepage");
  $meta_key = "_yoast_wpseo_title";
  $meta_value = jet_engine()->listings->data->get_option( 'pwp-options::seo-title-homepage' );

  isset($page, $meta_value) ? update_post_meta($page->ID , $meta_key, $meta_value) : false;

  return;
}

add_action('updated_postmeta', 'seoHomepageTitle');

Solution

  • You can remove the hook before updating, then adding it back like this

    function seoHomepageTitle() {
      $page = get_page_by_title("Homepage");
      $meta_key = "_yoast_wpseo_title";
      $meta_value = jet_engine()->listings->data->get_option( 'pwp-options::seo-title-homepage' );
      
      remove_action('updated_postmeta', 'seoHomepageTitle');
     
      isset($page, $meta_value) ? update_post_meta($page->ID , $meta_key, $meta_value) : false;
    
      //add_action('updated_postmeta', 'seoHomepageTitle');
      return;
    }
    
    add_action('updated_postmeta', 'seoHomepageTitle');