So I installed the Yoast SEO plugin, and tested your code, and now I can positively say “neither no nor yes, but you could” to this question:
Please help not sure whether I should use this along with
transition_post_status
transition_post_status
is fired before the wp_insert_post
action is fired, and the Yoast SEO plugin is actually saving (adding/updating) all its custom fields via the wp_insert_post
action:
// See WPSEO_Metabox::save_postdata() (in wordpress-seo/admin/metabox/class-metabox.php)
add_action( 'wp_insert_post', array( $this, 'save_postdata' ) );
So your code itself works, and the fields do get updated (if the new and current values are not the same and that all the if
conditions are met, of course); however the Yoast SEO plugin overrides the value via the WPSEO_Metabox::save_postdata()
function, which should answer this question:
I was able to solve the issue by using ‘
wp_insert_post
‘ action . Can
I know why other actions failed but ‘wp_insert_post
‘ worked?
Why did I say neither no nor yes, but you could?
Because you can use transition_post_status
along with wp_insert_post
like so:
add_action( 'transition_post_status', 'do_updated_to_publish', 10, 2 );
function do_updated_to_publish( $new_status, $old_status ) {
if ( $new_status !== $old_status && 'publish' === $new_status ) {
add_action( 'wp_insert_post', 'updated_to_publish', 10, 2 );
}
}
function updated_to_publish( $post_id, $post ) {
// Remove it; it will be re-added via the do_updated_to_publish() function,
// if necessary or when applicable.
remove_action( 'wp_insert_post', 'updated_to_publish', 10, 2 );
if ( ! defined( 'WPSEO_VERSION' ) || 'l' !== $post->post_type ) {
return;
}
if ( get_field( 'advanced_option_edit_seo', $post_id ) ) {
// Make your update_post_meta() calls here.
update_post_meta( $post_id, '_yoast_wpseo_focuskw', 'test' );
error_log( 'focuskw updated for post #' . $post_id );
}
}
Tried and tested working with Yoast SEO version 9.1.