Site icon Hip-Hop Website Design and Development

How to create multiple Gutenberg blocks in one plugin

I have created a custom block and can create another one in the same plugin but it will get messy if I carry on because everything has to be done in the same index.js file and php file or so it would seem. This is new to me so perhaps there is a simple way to do this.

But I tried to create a blocks folder and then put a src folder in there as well as an index.js file, so each block folder basically had its own css file and js file etc. But when I run npm run start it does not create the build folders in the subfolders like it does in the root.

So my current folder structure looks like:

build 
index.php
package.json
src
 - index.js
 - index.scss

where I was wondering if I could have multiple blocks something like this perhaps

build
index.php
hero.php
call-to-action.php
package.json
blocks
 - hero
  -- src
    --- index.js
    --- index.scss
 - call-to-action
  -- src
   --- index.js
   --- index.scss

package.json

{
  "name": "custom-blocks",
  "version": "1.0.0",
  "description": "",
  "main": "index",
  "scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@wordpress/scripts": "^19.1.0"
  }
}

index.php

<?php
/*
Plugin Name: custom blocks
Description: custom blocks
Version: 1.0
Author: ...
Author URI: ...
License: GPLv2 or later
*/

if ( ! defined( 'ABSPATH' ) ) exit;

class myCustomBlocks {
    function __construct() {
        add_action('init', array($this, 'adminAssets'));
    }
    
    function adminAssets() {
        wp_register_style('quizeditcss', plugin_dir_url(__FILE__) . 'build/index.css');
        wp_register_script('ournewblocktype', plugin_dir_url(__FILE__) . 'build/index.js', array('wp-blocks', 'wp-element', 'wp-editor'));
        register_block_type('ourplugin/hero-block', array(
            'editor_script' => 'ournewblocktype',
            'editor_style'  => 'quizeditcss',
            'render_callback' => array($this, 'theHTML')
        ));
    }

    function theHTML($attributes) {
       ob_start(); ?>
            <p>Here is some data: <?php echo esc_html($attributes['someAttribute']); ?></p>
       <?php return ob_get_clean();
    }
}

$myCustomBlocks = new myCustomBlocks();

index.js

import "./index.scss";
import {
  TextControl,
  Flex,
  FlexBlock,
  FlexItem,
  Button,
  Icon,
} from "@wordpress/components";

wp.blocks.registerBlockType("ourplugin/hero-block", {
  title: "Hero block",
  icon: "smiley",
  category: "common",
  attributes: {
    title: {
      type: "string",
    },
  },
  edit: EditComponent,
  save: function () {
    return null;
  },
});

function EditComponent(props) {
  return (
    <div className="some-jsx">
      Some block jsx here
    </div>
  );
}