3

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

  • Is this a Gutenberg bug or is there a work around? – David Labbe Sep 4 '18 at 1:10
2

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

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.