I need to get the page template name when the post is saved. It fails in save_post hook as $_POST('page_template') is not available. Gutenberg saves post via the REST API and uses WP_REST_Post_Controller->handle_template to save page template data. And like I said it does not make $_POST('page_template') available in save_post. It also looks like WP_REST_Post_Controller->handle_template fires after save_post hook.
I need to find a way to check the the page template being saved so that I can change the value being saved if needed.
Thanks

1 Answer
1

So I found a solution. There are 4 hooks that can be used to accomplish this depending on the exact needs.
The hooks are from wp-includes/meta.php in functions update_metadata() and add_metadata().

Hooks:
update_postmeta
updated_postmeta
add_post_meta
added_post_meta

These are called at different states and from the names it is pretty self self explanatory. add_post_meta and update_postmeta are called right before any DB changes and updated_postmeta and added_post_meta are called right after any changes to the DB.

Example:

//Example usage for updated and added.
 function page_template_check( $meta_id, $post_id, $meta_key, $meta_value ) {

    // Stop if not the correct meta key
    if ( $meta_key != '_wp_page_template' ) {
        return false;
    }

    //Do stuff here

};

add_action( 'added_post_meta', 'page_template_check', 10, 4 ); //after add
add_action( 'updated_postmeta', 'page_template_check', 10, 4 ); //after update

Leave a Reply

Your email address will not be published. Required fields are marked *