Search code examples
wordpresswordpress-theminggutenberg-blocks

Add custom block in a Wordpress block theme(Not with the plugin)


Basically I want to develop a wordpress block theme.For easy to customize I want to add some custom block in my theme.But I don't want to create a plugin for this.Custom block will be inside my theme.When someone install my theme he will get those custom block built in with my theme.How can I achive it and how can I organize my folder structure as well??


Solution

  • All you need to do is to create a src folder inside your theme then put your block folders there (shown structure below).

    Folder Structure may be:

    -- theme folder --> src --> block-folder > block files(edit.js, index.js, save.js etc.)

    For block files:

    Now it's time to install wp-scripts package to work with wp blocks. For that, Update your package.json file adding below lines. then in terminal go to the theme folder and command 'npm install' it will install all your dependencies packages then give the 'npm start' command.

    {
    "main": "build/index.js",
    "scripts": {
        "build": "wp-scripts build",
        "format": "wp-scripts format",
        "lint:css": "wp-scripts lint-style",
        "lint:js": "wp-scripts lint-js",
        "packages-update": "wp-scripts packages-update",
        "plugin-zip": "wp-scripts plugin-zip",
        "start": "wp-scripts start"
    },
    "devDependencies": {
        "@wordpress/scripts": "^23.4.0"
    }
    }
    

    Note: You need to register block via register_block_type function for PHP way or registerBlockType for JS way. Otherwise, above code won't work. Above codes will create your files only.