Yoast Seo Plugin – Set no-index to a post automatically when a post is set to sticky [closed]

In my effort to solve this I discovered a great resource for wordpress hooks for the job and found the right hook wpseo_saved_postdata here. Feel free to modify the code if you think it could be better. For now, it works for me.

function set_noidex_when_sticky($post_id){
        if ( wp_is_post_revision( $post_id ) ) return;
        //perform other checks

        //if(is_sticky($post_id)){ -----> this may work only AFTER the post is set to sticky
        if (isset($_POST['sticky']) == 'sticky') { //this will work if the post IS BEING SET ticky  
            add_action( 'wpseo_saved_postdata', function() use ( $post_id ) { 
            update_post_meta( $post_id, '_yoast_wpseo_meta-robots-noindex', '1' );
            }, 999 );
        }
}
 add_action( 'save_post', 'set_noidex_when_sticky' );

Only _yoast_wpseo_meta-robots-noindex was the meta I was targeting to change. Given below are some of yoast’s meta keys, if you wanna make any change using the code.

_yoast_wpseo_google-plus-description
_yoast_wpseo_linkdex
_yoast_wpseo_opengraph-description
_yoast_wpseo_redirect
_yoast_wpseo_canonical
_yoast_wpseo_sitemap-html-include
_yoast_wpseo_sitemap-prio
_yoast_wpseo_sitemap-include
_yoast_wpseo_meta-robots-adv
_yoast_wpseo_meta-robots-nofollow
_yoast_wpseo_meta-robots-noindex
_yoast_wpseo_metadesc
_yoast_wpseo_title