The post ACF validate_value Filter With post_ID appeared first on Justin Silver.
]]>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.
// 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.
Why reinvent the wheel? The above code is already included in Validated Field for ACF available in the WordPress repository.
The post ACF validate_value Filter With post_ID appeared first on Justin Silver.
]]>