最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rest api - WordPress Gutenberg get page template value when post updated?

programmeradmin5浏览0评论

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

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

Share Improve this question edited Sep 5, 2018 at 17:09 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Sep 3, 2018 at 13:43 David LabbeDavid Labbe 9337 silver badges21 bronze badges 1
  • Is this a Gutenberg bug or is there a work around? – David Labbe Commented Sep 4, 2018 at 1:10
Add a comment  | 

2 Answers 2

Reset to default 3

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

You could also get the page template slug of the post_id within the save_post function:

$template_slug = get_page_template_slug( $post_id );

if ( $template_slug !== 'template-name.php' ) {
    return;
}

// code away...
发布评论

评论列表(0)

  1. 暂无评论