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

Update post meta custom field using block editor

how to update post meta in a custom field in response to a user
interaction in the editor?

editPost() can be used for that, but https://developer.wordpress.org/block-editor/reference-guides/block-api/block-attributes/#meta-source-deprecated stated that:

Although attributes may be obtained from a post’s meta, meta attribute
sources are considered deprecated; EntityProvider and related hook
APIs

should be used instead, as shown in the Create Meta Block
how-to
.

So that means (in a function component), we should use useEntityProp to update a post meta via the block editor, which changes the post/editor state and then activates the submit button so that one can click on it to actually save the new meta value.

But then, here’s why it didn’t work

You commented that:

I’m verifying that changes aren’t being applied in two ways: visually
in the editor “custom fields” UI (after a page refresh) and by
checking the API output at ?feed=placepress_locations_public

Which means the “Custom Fields” meta box was enabled on the post editing screen (for your locations CPT), right?

Because if so, then you should know that the editor will make 2 AJAX requests:

  1. Request 1 will save the post title, content, meta, etc. via the REST API.

  2. Request 2 will save the active custom fields in the above meta box via the wp-admin/post.php route, where the request URL might look like so:

    https://example.com/wp-admin/post.php?post=149&action=edit&meta-box-loader=1&meta-box-loader-nonce=7be53e3b5b&_locale=user

Preview image

So that means, your api_coordinates_pp meta will be saved twice and thus I believe all your attempts/code for updating the meta actually worked, but then the value got overwritten via the second request above and because the block editor does not automatically update the meta in that meta box, then that’s why the value remained the same as when the meta box was initially loaded. I.e. The meta value remained the same as the one that was last saved.

How to easily fix/avoid the issue

  1. Change your meta to a protected meta, i.e. prefix the meta key with _ (an underscore).

  2. Or add your meta to the list of protected meta using the is_protected_meta filter:

    // Turn the api_coordinates_pp meta to a *protected* meta without having to change
    // the meta key (to _api_coordinates_pp).
    add_filter( 'is_protected_meta', 'wpse_408053_filter_is_protected_meta', 10, 3 );
    function wpse_408053_filter_is_protected_meta( $protected, $meta_key, $meta_type ) {
        return ( 'post' === $meta_type && 'api_coordinates_pp' === $meta_key ) ?
            true : $protected;
    }
    

So whether you used that filter or that you actually changed the meta key (to _api_coordinates_pp), the meta would now no longer be available in the “Custom Fields” meta box which then avoids the meta value from being overwritten.

PS: You could also update the meta in that meta box using JS, e.g. after calling updateMetaCoordinates(), but why bother with the extra code when the above options are easier 🙂

Additional Notes

  1. As I commented, you should use useEffect instead of the onload hack. You can see a full example here which uses Leaflet v1.8.0, and @wordpress/dom-ready for the view/front-end-only script, but the main parts are basically:

    function initMap( { clientId, attributes, setAttributes, updateMetaCoordinates } ) {
        const mapId  = 'map-' + clientId;
        const latLng = [ attributes.lat, attributes.lon ];
        const map    = L.map( mapId ).setView( latLng, 13 );
    
        ...
    
        const marker = L.marker( latLng, { draggable: true } ).addTo( map );
        const popup  = L.popup();
    
        ...
    
        const onDragend = e => {
            const latLng    = e.latlng || e.target.getLatLng();
            const latLngStr = latLng.lat + ',' + latLng.lng;
    
            openPopup( latLng, 'Current latitude & longitude: ' + latLngStr );
    
            setAttributes( {
                lat: latLng.lat,
                lon: latLng.lng,
            } );
    
            updateMetaCoordinates( latLngStr );
        };
    
        marker.on( 'dragend', onDragend );
        ...
    }
    
    function edit( props ) {
        const postType = useSelect(
            select => select( 'core/editor' ).getCurrentPostType(),
            []
        );
    
        const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
        const updateMetaCoordinates = value => {
            setMeta( { ...meta, api_coordinates_pp: value } );
            console.log( 'meta api_coordinates_pp set to ' + value );
        };
    
        const mapId = 'map-' + props.clientId;
    
        // Create the Leaflet map once this block has been attacted to the DOM.
        useEffect( () => initMap( { ...props, updateMetaCoordinates } ), [ mapId ] );
    
        return (
            <div { ...useBlockProps() }>
                <p>
                    Current latitude: { props.attributes.lat }<br />
                    Current longitude: { props.attributes.lon }
                </p>
                <div id={ mapId }
                    className="map-pp"
                    style={ { height: '180px' } }
                >
                    Loading map..
                </div>
            </div>
        );
    }
    

    And if you want, you can quickly try my block by downloading this plugin: wpse-408053.zip 🙂

  2. Leaflet has a plugin for React, so you might want to try/check it out: https://github.com/PaulLeCam/react-leaflet

Related Posts:

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

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
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 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