Need to find something?

Advanced Custom Fields Conditional Required Field

Advanced Custom Fields Conditional Required Field

Today I am going to share an easy way of setting conditionally required fields with the Advanced Custom Fields plugin. Normally we can set some complex conditions yet there is no way to set the field to be required or not required based on set conditions, using the default graphical UI of the Advanced Custom Fields plugin. Let’s check how we can do it with some custom functions.

The Senerio

Suppose you have a custom field called Property Type. Based on the value of the Property Type field, you want to set the Property Size field to be required or not required. Here in our project, If the property type is set to Rent, you want the Property Size field to be required, otherwise, it’s not required.

Our Function

First, we will validate the value of the Property Type field to see if it is equal to “Rent”. If so, we will set the Property Size field required. Add the following code to your theme’s functions.php file.

<?php

add_filter( 'acf/validate_value/name=property_size', 'validate_property_size_field', 10, 4 );

function validate_property_size_field( $valid, $value, $field, $input ){

  // bail early if value is already invalid
  if ( ! $valid ) { return $valid; }

  $property_type = $_POST['acf']['field_5f0aa92348bb6'];

  if ( $property_type == 'Rent' ){
    if ( ! $value ) {
      $valid = __( 'This field is required for Rental Properties' );
    }
  }

  return $valid;

}Code language: HTML, XML (xml)

Done! 😎 👌

Last Updated: February 26, 2021

Al-Mamun Talukder

About Al-Mamun Talukder

WordPress Developer. Minimalist Designer. Tech Enthusiast. Loves Cars. Founder of Omnixima.

Connect with me: Upwork, GitHub, Facebook, Twitter

Leave the first comment