Skip to content

Instantly share code, notes, and snippets.

@Luke1982
Created July 27, 2023 06:53
Show Gist options
  • Save Luke1982/3f23fca6de0ba9f529cfecf5c82ce1e8 to your computer and use it in GitHub Desktop.
Save Luke1982/3f23fca6de0ba9f529cfecf5c82ce1e8 to your computer and use it in GitHub Desktop.
Create Gutenberg theme-block
#!/bin/bash
# Setting up the arguments variables, so we can error on empty ones later
AUTHOR=
TITLE=
NAMESPACE=
GREEN="\033[0;32m"
NOCOLOR="\033[0m"
# Getting the passed arguments
while getopts "n:t:a:" option; do
case $option in
n) NAMESPACE=${OPTARG,,};;
t) TITLE=$OPTARG;;
a) AUTHOR=$OPTARG;;
esac
done
# Create a slug from the title
LOWERCASE_TITLE=${TITLE,,}
SLUG=${LOWERCASE_TITLE//" "/"-"}
FUNCTION_NAME=${LOWERCASE_TITLE//" "/"_"}
# Error out when the block directory already exists
if [[ -d "$SLUG" ]]; then
echo "Block directory already exists, please rename or remove"
exit 1
fi
# Error out when one of the arguments is missing
if [[ -z $AUTHOR ]] || [[ -z $NAMESPACE ]] || [[ -z $TITLE ]]; then
echo "Missing an argument. Pass n for namespace, t for title and a for author"
exit 1
fi
# Create the block directory and move into it
mkdir $SLUG
cd $SLUG
# Create the main PHP file
cat > ./index.php <<EOF
<?php
/**
* Index.php
*
* @author $AUTHOR
* @package $SLUG
*/
/**
* The registration file for the $TITLE block.
*/
function ${NAMESPACE}_${FUNCTION_NAME}_block_init() {
register_block_type( __DIR__ . '/build' );
}
add_action( 'init', '${NAMESPACE}_${FUNCTION_NAME}_block_init' );
EOF
# Create the block files and rename the directory to 'src'
npx @wordpress/create-block --no-plugin --namespace=$NAMESPACE $SLUG
mv $SLUG src
# Create package.json file
cat > ./package.json <<EOF
{
"name": "$SLUG",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "wp-scripts start",
"build": "wp-scripts build"
},
"author": "",
"license": "ISC",
"dependencies": {
"@wordpress/scripts": "^26.1.0"
}
}
EOF
# Install wp-scripts in main block directory
npm install
echo -e "Done! you can now change to directory ${GREEN}${SLUG}${NOCOLOR} and execute ${GREEN}npm start${NOCOLOR} to start developing your block"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment