Create an Advanced Custom Fields “Code” Field
Wish you could have a textarea in the Advanced Custom Fields plugin that would allow you to hit tab, so you could indent your content (and not just skip to the next line)?
As a theme developer, I often add ACF fields that I use to allow one to add code to various parts of the site, mostly CSS or JS. It’s annoying suprising that a field doesn’t exist within ACF to this, but it’s not terribly difficult to set this up on your own, if you have a little know how.
Note, this is a really simple setup. We’re just changing our field so that we can hit tab and get a tab. No other fancy code highlighting or anything.
Step 1: Functions.php
You’ll need this in your functions.php file:
// Adds Javascript for admin area
function your_admin_acf_scripts() {
wp_enqueue_script( 'crafted-acf-admin-js', get_template_directory_uri() . '/path/to/acf-admin.js', array(), '1.0.0', true );
}
add_action('acf/input/admin_enqueue_scripts', 'your_admin_acf_scripts');
Step 2: Javascript
See that/path/to/acf-admin.js in the code above?
That code will be looking for a file in your theme’s folder. So if your theme folder is cool-theme
, you would need to create a file in a folder like so:
cool-theme/path/to/acf-admin.js
You can, of course, put the file elsewhere in your theme, just make sure that path in our your_admin_acf_scripts()
points to it. You can always view source and search for the file while in /wp-admin/ to verify it’s there.
Next, add this code to your newly created JS file:
const matches = document.querySelectorAll('.code textarea');
matches.forEach((userItem) => {
userItem.addEventListener('keydown', function(e) {
if (e.key == 'Tab') {
e.preventDefault();
var start = this.selectionStart;
var end = this.selectionEnd;
// set textarea value to: text before caret + tab + text after caret
this.value = this.value.substring(0, start) +
"\t" + this.value.substring(end);
// put caret at right position again
this.selectionStart =
this.selectionEnd = start + 1;
}
});
});
Breaking it down quickly, this will find our ACF textareas:
const matches = document.querySelectorAll('.code textarea');
This will cycle through any and all “matches”:
matches.forEach((userItem) => {
And you can kind of read through the rest to see how the magic happens. Credit goes to kasdega and company for that.
Step 3: Add a Class to Your ACF Textareas
In ACF, and depending on the version or how much they change it in future, look for this Wrapper Attributes field, and add code
to the class field.
That’s it. Now the fields will look like so (I like using code
for the class, because it also makes the field immediately obvious as a “code” field and changes the textarea’s font to a monospace one.
Up Next: Click Optimize