Last active
July 7, 2022 21:08
-
-
Save f3bruary/5b862cd79a83da0cd90b5f121a38417b to your computer and use it in GitHub Desktop.
NPM script to create ACF layout directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
/* | |
* Create ACF Flexible Layouts | |
*/ | |
// Require modules. | |
const fs = require( 'fs' ); | |
const args = process.argv.slice( 2 ); | |
const blockname = args[ 0 ]; | |
if ( ! blockname ) { | |
console.error( '\x1b[31m%s\x1b[0m', '> No blockname entered' ); | |
process.exit( 1 ); | |
} | |
// Protect against non-alphanumeric characters | |
if ( ! /^[a-z0-9]+$/.test( blockname ) ) { | |
console.error( '\x1b[31m%s\x1b[0m', '> Invalid blockname' ); | |
process.exit( 1 ); | |
} | |
// Protect against null byte poisoning | |
if ( blockname.indexOf( '\0' ) !== -1 ) { | |
console.error( '\x1b[31m%s\x1b[0m', '> Invalid blockname' ); | |
process.exit( 1 ); | |
} | |
const dir = `${ __dirname }/../theme/blocks/${ blockname }`; | |
// acf.php | |
const fields = `<?php | |
$blockname = '${ blockname }'; | |
$layouts[$blockname] = array( | |
'order' => 4, | |
'key' => "layout_$blockname", | |
'name' => $blockname, | |
'label' => '${ blockname }', | |
'display' => 'block', | |
'sub_fields' => array( | |
// Fields | |
), | |
); | |
`; | |
// blockname.php | |
const template = `<?php | |
$blockname = basename(__FILE__, '.php'); | |
$prefix = "$blockname-"; | |
$var = get_sub_field($prefix . 'var'); | |
?> | |
<!-- <?= $blockname; ?> --> | |
<section class="<?= $blockname; ?>"> | |
<div class="container"> | |
<!-- content --> | |
</div> | |
</section> | |
<!-- end:<?= $blockname; ?> --> | |
`; | |
if ( blockname ) { | |
if ( ! fs.existsSync( dir ) ) { | |
// Create dir | |
fs.mkdirSync( dir ); | |
// Create acf.php | |
fs.writeFileSync( `${ dir }/acf.php`, fields, ( err ) => { | |
if ( err ) { | |
console.error( err ); | |
} | |
} ); | |
// Create blockname.php | |
fs.writeFileSync( `${ dir }/${ blockname }.php`, template, ( err ) => { | |
if ( err ) { | |
console.error( err ); | |
} | |
} ); | |
console.log( '\x1b[32m%s\x1b[0m', '> Block successfully created' ); | |
} else { | |
console.error( '\x1b[31m%s\x1b[0m', '> Block already exists' ); | |
process.exit( 1 ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment