2

I'm trying to save post id and keyword (Yoast Focus Keyword) to a custom table when post is created or updated via save_post action. It saves everything fine on Publish (first-time) but when I update the post, it gets old value for focus keyword from database and doesn't save the new value.

for example Focus Keyword (Publish) = "Hello World" (works fine and keyword is stored properly) Focus Keyword (1st Update) = "Hello" (Doesn't work and keeps "Hello World" in custom table) Focus Keyword (2nd Update) = "Hello again" (It saves "Hello")

So basically the problem is that get_post_meta($post_id, '_yoast_wpseo_focuskw', true) returns which is already in the database and not the new value that is being saved.

What is the best way to get the new value while the post is being saved via save_post action?

$_POST['_yoast_wpseo_focuskw'] won't work because Yoast Focus Keyword input field doesn't have name set on input field. Screenshot

Any help would be appreciated. Thanks

This is my code.

add_action('save_post', 'my_custom_table');
function my_custom_table($post_id) {
    global $wpdb;
    $table_name = $wpdb->prefix . "custom_table";

    $data = [
        'post_id' => $post_id,
        'keyword' => get_post_meta( $post_id, '_yoast_wpseo_focuskw', true )
    ];

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
        return;
    } else {

        //check if new post so insert
        if( strpos( wp_get_raw_referer(), 'post-new' ) > 0 ) {

            if (get_post_status($post_id) === 'publish') {

                $wpdb->insert( 
                    $table_name, 
                    $data
                );

            }

        } else {

            $wpdb->update( 
                $table_name, 
                $data,
                array( 
                    'post_id' => $post_id
                ),
                array( '%d', '%s' ),
                array( '%d' )
            );
        }

    }

}
2

WordPress fires the updated_{$meta_type}_meta hook which fires after the metadata is updated. In your case, the hook would be updated_post_meta and you could have your function run on that hook instead of the save_post hook.

1
  • Thanks. :) It's working.
    – Key
    Sep 23 at 15:56
0

It really depends on when _yoast_wpseo_focuskw is actually written/updated in the plugin you're working with. That's where I'd start. Try and track it down, is it being written on post_save as well? Or earlier? Probably later. Somewhere around WPSEO_Meta::set_value() #, can backtrace from there.

Then adapt your code to that, queuing whatever you're doing after the new value has been written.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.