1

I've created a block, and I need to save as post_meta a value from an action on the panel.

Php side:

add_action( 'init', 'yasr_gutenberg_show_in_rest_overall_meta' );

function yasr_gutenberg_show_in_rest_overall_meta() {
    register_meta( 'post', 'yasr_overall_rating',
        array(
            'show_in_rest' => true,
            'single' => true,
            'type' => 'number',
        )
    );
}

Then in js, I do this:

attributes: {
            //name of the attribute
            overallRating: {
                type: 'number',
                source: 'meta',
                meta: 'yasr_overall_rating'
            },
}

edit:
     function( props ) {

                 const { attributes: {overallRating}, setAttributes, isSelected } = props;

                /***
                Action and ajax action to update metadata 
                 and where I use setAttributes to 
                update overallRating
                ***/

     }

Everything seems to work, but when save or update the post, the overallRating get again the initial value, instead of the new one just saved fine with the ajax call.

How can I achieve this?

2 Answers 2

1

I found out this bug https://github.com/WordPress/gutenberg/issues/4989

If an attribute get data from meta, and then post is saved/updated, it always return as undefined

3
  • 2
    That's not exactly what this bug is about. I think your issue here is that you are not using register_post_meta to properly register your meta field so that its' accessible via the REST API.
    – swissspidy
    Jun 6, 2019 at 16:43
  • it is this bug indeed github.com/WordPress/gutenberg/issues/13621 that is a duplicate of the above one. register_post_meta seems like was good
    – Dudo1985
    Jun 6, 2019 at 20:02
  • @swissspidy after more than an year again here to say that you were right :)
    – Dudo1985
    Dec 3, 2020 at 10:14
1

Since this question and my previous answer was updated recently, I'm answering again with the solution:

Just like swissspidy said in his comment, it was because the register_meta function (and init action) was in the wrong place. It was in a file invoked only in the backend (under is_admin()) Instead, it must be in both back end and front end, even if used only by Gutenberg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.