Adding an Input Mask to ACF Fields Using Javascript

Problem: How can I add an input mask to an ACF field in the WordPress backend using  jQuery?

I need to enforce a specific input format (like a phone number, date, or currency) for a custom field created using Advanced Custom Fields (ACF) in the WordPress backend. However, ACF doesn’t have built-in options for adding input masks.


Solution:

To add an input mask to an ACF field, you can use the jQuery Input Mask library. This method lets you control the input format directly in the WordPress admin panel.

Steps:

  1. Install and Enqueue jQuery Input Mask:
    • First, you need to enqueue the jQuery Input Mask library in your WordPress admin.

    Add this code to your theme’s functions.php file:

    function enqueue_acf_input_mask() {
    // Enqueue the jQuery Input Mask script
    wp_enqueue_script( 'jquery-input-mask', 'https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.7/jquery.inputmask.min.js', array('jquery'), '5.0.7', true );

    // Enqueue your custom script to apply the input mask
    wp_enqueue_script( 'acf-input-mask', get_template_directory_uri() . '/js/acf-input-mask.js', array('jquery-input-mask'), '1.0.0', true );
    }
    add_action('admin_enqueue_scripts', 'enqueue_acf_input_mask');
  2. Identify the ACF Field:
    • Each ACF field in the backend has a unique input ID. You can find this ID by inspecting the field in your browser’s developer tools.
    • The ID format is usually: #acf-field_<field_name>.
  3. Create a Custom jQuery Script:
    • In your theme, create a file called acf-input-mask.js in the js folder and add the following code:
    • jQuery(document).ready(function($) {
      // Apply the input mask to a specific ACF field
      $('#acf-field_<field_name>').inputmask('999-999-9999'); // Example mask for phone number
      });
    • Replace <field_name> with the actual field name or ID from your ACF field.
    • Customize the input mask pattern according to your requirements. For example
    • 999-999-9999 for a phone number.
    • 99/99/9999 for a date.
    • $ 999,999.99 for currency.

4 Test the Input Mask:

  • After adding the script, the input mask should automatically apply to the specified ACF field when editing a post or page in the WordPress backend.

Example Use Case:

Let’s say you have an ACF field called “phone_number” and you want to enforce a phone number format. The jQuery code would look like this:

jQuery(document).ready(function($) {
$('#acf-field_phone_number').inputmask('999-999-9999'); // Phone number mask
});

Conclusion:

Using jQuery Input Mask, you can easily add format validation to ACF fields in the WordPress admin panel. This approach gives you greater control over input formatting, ensuring consistent data entry for custom fields.

 

Related Blog

Sign up for our newsletter to stay up to
date with tech news!