WordPress

WordPress Gutenberg accordion block

const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;

registerBlockType( 'my-plugin/accordion', {
	title: __( 'Accordion', 'my-plugin' ),
	icon: 'format-status',
	category: 'layout',
	attributes: {
		title: {
			type: 'array',
			source: 'children',
			selector: '.accordion-title'
		},
		content: {
			type: 'array',
			source: 'children',
			selector: '.accordion-content'
		}
	},
	edit: props => {
		const { attributes: { title, content }, setAttributes } = props;
		
		const onChangeTitle = newTitle => {
			setAttributes( { title: newTitle } );
		};
		
		const onChangeContent = newContent => {
			setAttributes( { content: newContent } );
		};
		
		return (
			<div className="accordion">
				<RichText
					tagName="h3"
					className="accordion-title"
					value={ title }
					onChange={ onChangeTitle }
					placeholder={ __( 'Accordion Title', 'my-plugin' ) }
				/>
				<RichText
					tagName="div"
					className="accordion-content"
					value={ content }
					onChange={ onChangeContent }
					placeholder={ __( 'Accordion Content', 'my-plugin' ) }
				/>
			</div>
		);
	},
	save: props => {
		const { attributes: { title, content } } = props;
		
		return (
			<div className="accordion">
				<h3 className="accordion-title">{ title }</h3>
				<div className="accordion-content">{ content }</div>
			</div>
		);
	}
} );

This code creates a Gutenberg block that has two RichText components, one for the title and one for the content. The attributes object defines the data structure for the block and the edit and save functions define how the block should be displayed in the editor and on the front-end, respectively.

register block

// Register the block in the theme
add_action( 'init', 'register_accordion_block' );
function register_accordion_block() {
    // Register the block script
    wp_register_script( 
        'accordion-block-script', 
        get_theme_file_uri( '/js/accordion-block.js' ), 
        array( 'wp-blocks', 'wp-element' ), 
        filemtime( get_theme_file_path( '/js/accordion-block.js' ) ) 
    );

    // Register the block styles
    wp_register_style( 
        'accordion-block-style', 
        get_theme_file_uri( '/css/accordion-block.css' ), 
        array( 'wp-blocks' ), 
        filemtime( get_theme_file_path( '/css/accordion-block.css' ) ) 
    );

    // Register the block
    register_block_type( 'my-theme/accordion-block', array(
        'editor_script' => 'accordion-block-script',
        'editor_style'  => 'accordion-block-style',
        'style'         => 'accordion-block-style',
    ) );
}