• I have a task to make user able to enter bunch of dates with the post meta so i can query them in my theme later. I found a great example to create single text metabox in the gutenberg but as far as I know WordPress allows to store multiple values in a one meta field (I’d use get_post_meta() with parameter $single = false to get it with PHP). Now I wasted a half of the day and stuck on this step, when my code doesn’t work and I lack an expirience with React, so I wish anyone will put me on the right way.

    When button clicked array actually increased but the fields not always rendered plus i cannot really edit the text. Here is my code:

    
    registerBlockType( 'sonnet/sn-spectacle--datetime', {
    	title: 'Meta Block',
    	icon: 'smiley',
    	category: 'common',
    
    	attributes: {
    		dates: {
    			type: 'array',
    			source: 'meta',
    			meta: 'sn-spectacle__datetime',
    		},
    	},
    
    	edit( { className, setAttributes, attributes } ) {
    		function handleChange( value, index ) {
    			const { dates } = attributes;
    			dates[index] = value;
    			setAttributes({dates});
    		}
    		function addDate() {
    			const { dates } = attributes;
    			dates.push('');
    			setAttributes({dates});
    		}
    
    		return (
    			<div className={ className }>
    				{ attributes.dates.map((date, index) => {
    					return <TextControl
    						key={index}
    						label="Test"
    						value={ attributes.dates[index] }
    						onChange={ value => handleChange(value, index) }
    					/> })}
    				<Button onClick={ addDate }>+</Button>
    			</div>
    		);
    	}
    } );
    

    Maybe anyone already made such thing, I didn’t found any examples.

    • This topic was modified 4 years, 11 months ago by Mikhail.
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Gutenberg custom block with array’ is closed to new replies.