WordPress
ACF validate_value Filter With post_ID

Advanced Custom Forms Pro 5.0 is out, and it contains a major overhaul to the way that custom fields are handled. It also had a major impact on the way that third-party add-ons were written to extend ACF functionality which meant that it was considerable work to refactor my Validated Fields plugin to support the new architecture. The new architecture is definitely superior in my opinion and has some great new filters that we can leverage such as
acf/validate_value and its siblings acf/validate_value/type={$field_type}, acf/validate_value/name={$field_name}, acf/validate_value/key={$field_key}.
Unfortunately this filter does not have the post_ID available to it, which greatly limits the range of things we can do with it. To work around this I found that by inserting a field named acf[post_ID] into the editor form - and the "acf" part is critical - it would be picked up and submitted with the rest of the form values. This meant that it would be available in the $_POST, really opening up the possibilities.
Sample Code
// use a unique value to prevent conflicts with other ACF fields
define( 'MY_ACF_FORM_VALUES', 'MY_ACF_FORM_VALUES' );
// add the post_ID to the acf[] form
function my_edit_form_after_editor( $post ){
print( "<input type='hidden' name='acf[%1$s][post_ID]' value='%2$d'/>",
MY_ACF_FORM_VALUES,
$post->ID
);
}
add_action( 'edit_form_after_editor', 'my_edit_form_after_editor' );
// use the post_ID in your validation function
function my_validate_value( $valid, $value, $field, $input ) {
$post_id = $_POST['acf'][MY_ACF_FORM_VALUES]['post_ID'];
// more code!
return $valid;
}
add_filter( "acf/validate_value", 'my_validate_value', 10, 4 );
The rest of the my_validate_value() will be up to you.
Conversation 8
is_admin()- I copied this from Validated Field which does some other things that do require the admin check. Since I wrote this post I realized it's probably prudent to use something likeacf[my_unique_sub_array][post_id]or similar to prevent conflicts with ACF should you ever have a field namedpost_ID. A lot of new features being added in version 2.0 if you care to check it out: https://github.com/doublesharp/validated-field-for-acf