Search code examples
javascriptwordpresswordpress-gutenberg

setMeta in gutenberg block saves the meta value in multiple rows instead of one row


I am writing a gutenberg block which saves the data into meta fields. Problem is that the value is being saved in multiple rows in the database instead of one. How can I save in one row?

For example: 'My apple' is saved as metakeyname: My and metakeyname: apple into the database. I want to save it as metakeyname: My apple

Below is my code. Please help. Thank you!

const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { RichText, PlainText, MediaUpload, InspectorControls } = wp.editor;
const { TextControl, Tooltip, PanelBody, PanelRow, FormToggle, Button } = wp.components;
const el = wp.element.createElement;

registerBlockType('my/fields', {
    title: 'My Fields',
    description: 'Fill in the required data and press the Update button above',
    icon: 'products',
    category: 'common',
    attributes: {
        sku: {type: 'string'},
        
        pdf: {type: 'string'},
        gallery: {type: 'string'},
        features: {type: 'string'},
        brands: {type: 'string'},
        category: {type: 'string'},
    },
    
    edit: (props) => { 
    const { attributes, setAttributes } = props;
    const [meta, setMeta] = wp.coreData.useEntityProp('postType', 'post', 'meta');

        
return el(
  "div",
  null,
   el(
    "h3",
    null,
    "Please enter Product name above & details below"
  ),
   el(TextControl, {
    label: "SKU:",
    value: attributes.sku,
    onChange: (newtext) => setAttributes({ sku: newtext }) & setMeta({sku: newtext})        
  })
);
        
    },
    
    save: function(props) {
            return props.attributes.sku;
    }
    
})

Solution

  • I got it finally. I had to define single = true and type while making the particular field available in the rest api.

    // Meta in REST API
    add_action( 'rest_api_init', 'my_register_meta_fields');
    function my_register_meta_fields() {
        register_meta( 'post', 'sku', array(
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
        ));
    }