Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Transition from (classical) serialized custom meta field to (gutenberg) rest enabled meta

Here’s an answer to question 1 that uses register_post_meta. It’s also the start of an answer to question 2 by use of the prepare_callback option in show_in_rest .

add_action( 'init', 'wpse_89033_register_custom_meta' );
function wpse_89033_register_custom_meta() {

    $post_types = [ 
        'post',
        'page',
        'attachment',
    ];

    foreach ( $post_types as $post_type ) {

        register_post_meta( 
            $post_type,
            '_custom_key',
            array(
                'type'              => 'string',
                'single'            => true,
                'auth_callback'     => function() { 
                    return current_user_can( 'edit_posts' );
                },
                'show_in_rest'      => [
                    'prepare_callback' => function( $value ) {
                        return wp_json_encode( $value );
                    }
                ],
            ) 
        );

    }

}

The documentation for show_in_rest (see register_meta) says it’s a boolean parameter. But it will accept an options array. To see the options, look at the body of get_registered_fields, in particular the value of $default_args. The prepare_callback overrides prepare_value, the method in WP_REST_Meta_Fields that converted your custom meta value from an array to a string. With our callback, that array will instead be encoded as JSON.

On the JavaScript side, here are some key declarations.

// Get the custom meta
let customMeta = wp.data.select('core/editor').getEditedPostAttribute('meta');

// Parse the meta so you can do some JS with it
let parsed = JSON.parse(customMeta._custom_key);

// Do some JS with the parsed meta...

// Stringify the parsed meta before dispatching it
let stringified = JSON.stringify(parsed);

/*
 * Dispatch (update) the meta (and don't forget to
 * save/publish/update the post to ensure the meta goes in the database)
 */ 
wp.data.dispatch('core/editor').editPost({meta: {_custom_key: stringified}}); 

Back in PHP land, getting and updating your custom meta will now work differently. When you call get_post_meta, you’re used to getting an array, and you’ll probably still want one sometimes. But if you last updated your custom meta via the WP REST API, you’re getting a JSON string. In that case, you’ll have to use json_decode. One approach would be to wrap calls to get_post_meta like so:

function wpse_89033_get_custom_meta( $post_id, $meta_key ) {

    $post_meta = get_post_meta( $post_id, $meta_key, true );

    // If $post_meta is a string that's not empty
    if ( $post_meta && is_string( $post_meta ) ) {

        /*
         * Use the decoded JSON string or else the original string 
         * if decoding fails, e.g., if the string isn't JSON
         */ 
        $post_meta = json_decode( $post_meta, true ) ?: $post_meta;

    }

    return $post_meta;

}

If you make changes to your custom meta as an array, don’t worry about re-encoding before calling update_post_meta. The prepare_callback will handle re-encoding.

About updating in PHP, calling update_post_meta during save_post, as shown in the official plugin handbook, appears to override updates made via the WP REST API. So one more thing to consider is conditioning any save_post update to your custom meta on whether the post is being edited in Gutenberg. If it is, leave the update to the REST API.

Related Posts:

  1. Custom meta POST request fired twice when updating a post in Gutenberg
  2. How to get custom post meta using REST API
  3. Cannot edit post meta fields with rest API
  4. How to save a ToggleControl value in a meta field?
  5. Custom Meta Box not Saving in Posts with Gutenberg Editor
  6. WordPress Rest API to call page data associate with custom meta
  7. Add post meta fields, when creating a post using WordPress’ REST API
  8. Looping inside block return
  9. Update post meta custom field using block editor
  10. How to add a post’s view count into the WordPress API response
  11. WordPress Blocks, setAttributes not saving
  12. Can’t set custom meta fields for a post
  13. Make Custom Fields Public in JSON – API
  14. Block Editor – Meta values not saved, meta changes to empty array on update
  15. What is the best way to get a different post’s custom field/postmeta with js?
  16. Can I exclude a post by meta key using pre_get_posts function?
  17. Custom post meta field effect on the performance on the post
  18. Difference between meta keys with _ and without _ [duplicate]
  19. Orderby meta_value only returns posts that have existing meta_key
  20. What is the index [0] for on post meta fields?
  21. What is “meta_input” parameter in wp_insert_post() used for?
  22. How to enable revisions for post meta data?
  23. The “_encloseme” Meta-Key Conundrum
  24. Best way to programmatically remove a category/term from a post
  25. Gutenberg add a custom metabox to default blocks
  26. Using get_post_meta with new_to_publish
  27. Is there a way to get protected meta fields through any of the available built-in WordPress APIs? (xmlrpc, wp-json)
  28. How to return Meta data from the REST API?
  29. Add metabox to document tab in gutenberg
  30. Custom field metabox not showing in back-end
  31. So much data in postmeta
  32. Can I count the number of users matching a value in a multiple value key?
  33. When using add_post_meta and update_post_meta, is there any way to give the individual arrays keys?
  34. How to hide meta box values from custom fields list?
  35. Auto sort the wp-admin post list by a meta key
  36. get_post_meta() unserialize issue – returns boolean(false)
  37. What is the advantage of the wp_options design pattern?
  38. Storing meta fields multiple times OR once with multi dimensional array?
  39. Allow user to create instances of custom field
  40. extend Meta Box / Document Panel
  41. display specific custom fields
  42. Is there a hook / action that is triggered when adding or removing a post thumbnail?
  43. Meta keywords and descriptions plugin for manually editing meta for each page/post
  44. getEntityRecord without knowing the post type
  45. Retrieve custom fields on Categories, using WP-API
  46. How to filter or search the posts using postmeta tables custom meta fields with wordpress REST API
  47. passing argument to get_template_part() or a better way to code
  48. Is it possible to store arrays in a custom field?
  49. Get updated meta data after save_post hook
  50. Multiple meta values for same meta_key adding on “Preview Changes” hit but not on saving or updating post
  51. Save HTML formatted data to post meta using add_post_meta()
  52. importing data from non-wordpress mysql db
  53. Gutenberg Custom Block
  54. Create meta boxes that don’t show in custom fields
  55. Transients vs CRON +Custom Fields: Caching Data Per Post
  56. Unable to save datetime custom meta field using update_post_meta() function
  57. Up/Down voting system for WordPress
  58. post meta data clearing on autosave
  59. Create custom field on post draft or publish?
  60. Display info from custom fields in all images’ HTML
  61. Ordering posts by anniversary using only day and month
  62. get_post_meta fields don’t show up on posts page
  63. Update meta values with AJAX
  64. How to break meta values into different items and avoid duplicates?
  65. copy attachments to another post type and change attachment url
  66. ajax delete value from custom field array
  67. Save attachment custom fields on front end
  68. How to use pagination with get_post_meta
  69. Copying Custom Meta Values from existing post to a duplicate post
  70. Add a post meta key and value only if it does not exist on the post
  71. Move value of one custom field to another
  72. Order posts according to user defined order for meta values?
  73. Displaying posts with only upcoming dates according their custom field date value
  74. Custom fields to save multiple values
  75. Custom fields: In what order are they saved into the DB?
  76. Function to change meta value in database for each post
  77. Get a post_id where meta_value equals something in a serialized meta_value field
  78. Get aggregate list of all custom fields for entire blog
  79. Unable to show ACF’s Image Custom Field properly in Genesis Framework [closed]
  80. Custom field value based on other custom field values
  81. wp_handle_upload error “Specified file failed upload test” but still creates attachment?
  82. Which is best in the following scenario : post_meta vs custom table vs parent/child posts
  83. Saving custom image meta fields
  84. Author Page Custom Query WHERE author OR [post meta value] OR [post meta value]
  85. How to display Meta Field Value?
  86. MySQL query to set wp_postmeta using term_taxonomy_id value
  87. woocommerce product custom field
  88. How to Validate Post Meta type/extension (Video File Image File etc)
  89. Get all meta keys assigned to a post type
  90. using multiple meta_key and meta_value in query_posts
  91. Save/update post_meta with Gutenberg from the panel
  92. Register rest field for specific user
  93. Adding custom fields (post meta) before/during wp_insert_post()
  94. Combine multiple custom field values into single value
  95. How can I sort homepage by a meta value?
  96. Get specific custom field keys from a post and put into an array
  97. How do I use wp_query for WordPress search?
  98. Nav Menu – Add class based on meta keys
  99. How to query posts with certain custom meta data, and output Post data
  100. MySQL Query that looks for post with Custom Field, then changes Category
Categories custom-field Tags block-editor, custom-field, post-meta, rest-api
admin-ajax.php mixed content
Using docker with wordpress, how to handle backups correctly?

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress