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. What is the best way to get a different post’s custom field/postmeta with js?
  19. Can I exclude a post by meta key using pre_get_posts function?
  20. What is the index [0] for on post meta fields?
  21. Best way to programmatically remove a category/term from a post
  22. Custom field metabox not showing in back-end
  23. How to hide meta box values from custom fields list?
  24. What is the advantage of the wp_options design pattern?
  25. display specific custom fields
  26. Meta keywords and descriptions plugin for manually editing meta for each page/post
  27. Multiple meta values for same meta_key adding on “Preview Changes” hit but not on saving or updating post
  28. Transients vs CRON +Custom Fields: Caching Data Per Post
  29. Unable to save datetime custom meta field using update_post_meta() function
  30. Create custom field on post draft or publish?
  31. Display info from custom fields in all images’ HTML
  32. get_post_meta fields don’t show up on posts page
  33. Update meta values with AJAX
  34. copy attachments to another post type and change attachment url
  35. Cannot edit post meta fields with rest API
  36. Add a post meta key and value only if it does not exist on the post
  37. Custom fields to save multiple values
  38. Function to change meta value in database for each post
  39. Get aggregate list of all custom fields for entire blog
  40. wp_handle_upload error “Specified file failed upload test” but still creates attachment?
  41. How to sort category by custom field value
  42. trim custom field text value and show (…)
  43. using multiple meta_key and meta_value in query_posts
  44. Adding custom fields (post meta) before/during wp_insert_post()
  45. MySQL Query that looks for post with Custom Field, then changes Category
  46. ACF: How to get the full field name (meta_key) by a field key?
  47. post meta getting deleted on save
  48. How to add a new meta key and assign timestamp to posts
  49. Custom field not updating when value is empty
  50. meta_compare seems to be treating values as strings instead of integers as expected
  51. Print custom field in Query Loop block
  52. Limit the number of acf content when displaying in post loop [closed]
  53. Read / Watch / Listen times – meta
  54. How to add custom metadata text box dropdown to sidebar in Gutenberg editor for all post types
  55. Displaying multiple URLs as custom field values
  56. Show values of custom post meta on ‘Add new post’ page?
  57. Custom post meta field effect on the performance on the post
  58. get_posts in meta box dropdown not showing latest posts
  59. Limits, not all post are showen when querying for posts by view count
  60. Display Custom Meta Box Field Only If Value is Present
  61. Ordering posts by custom field named “date” in backend
  62. Best way to store everyday post views?
  63. Branch made by several custom values
  64. WordPress creates new lines in postmeta table on post update
  65. How to add custom filed value after in wp post title
  66. Sortable Custom Columns not sorting correct
  67. User customising position of WordPress Featured Image
  68. Can I save post meta programatically without setting metaboxes?
  69. Insert image into sub-field with update_post_meta
  70. How to use conditional statement with custom field
  71. Meta box values are displayed on Custom Fields list. Is it possible to hide them?
  72. Best way to achieve multiple links in a post title
  73. How can I add/update post meta in a admin menu page?
  74. Show array of meta_value in Edit Post Coloum
  75. Get author total post votes from post meta
  76. Group Posts By Custom Meta Value: Date
  77. custom filed from post in the side bar
  78. Making WP_Query limit results by date before today where date is a meta_query
  79. How to display custom fields in hestia theme
  80. How to speed up post list slowed by update_meta_cache()?
  81. Query to sort a list by meta key first (if it exists), and show remaining posts without meta key ordered by title
  82. SQL query to change the value of a Custom Field
  83. Add custom field information to source meta data
  84. Update custom field on page specific to logged in user
  85. 4 Unique Random Posts based on Custom Field Values
  86. Create Meta boxes dynamically
  87. Delete custom meta
  88. Check if value exists before saving
  89. Get meta value when the page is a blog archive
  90. change attachment custom field onChange event
  91. wordpress simple post multi rating with post_meta and user_meta
  92. wp_postmeta are updated for only one page
  93. Custom fields / meta box output
  94. Colecting values from custom field checkboxes and displaying them in the post
  95. Build Array from Input Fields question
  96. How can i put a custom field inside this php
  97. Custom Fields after update to WordPress 6
  98. How to add new Metadata options (Date, Author, etc.) for Posts?
  99. Search for meta_query does not return any result if combined with title
  100. Can I count every article following extracted meta value?
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
  • 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