acf/validate_attachment

Overview

This filter allows you to perform custom validation on an attachment and prevent it being uploaded or selected for a specific field.

Similar to the acf/upload_prefilter filter, this filter can be used to prevent an upload, however, it can also be used to prevent an attachment being selected from a WP media modal.

Changelog

  • Added in v5.2.8
  • Added context parameter in v5.6.3

Parameters

$errors = apply_filters("acf/validate_attachment", $errors, $file, $attachment, $field);
  • $errors (array) An array of error messages (strings) for the given attachment. Appending to this array will result in the attachment failing to upload, and the error message displayed to the client.
  • $file (array) An array of generic file data including type, width, height and size
  • $attachment (array) The attachment being uploaded/displayed. This data changes depending on context
  • $field (array) The field array containing all attributes & settings
  • $context (string) Description of the current context: upload, basic_upload (when uploading) or prepare (when viewing). Added in 5.6.3

Usage

There are 4 ways to hook into this filter:

  1. acf/validate_attachment – filter for every field
  2. acf/validate_attachment/type={$field_type} – filter for a specific field based on itโ€™s type
  3. acf/validate_attachment/name={$field_name} – filter for a specific field based on itโ€™s name
  4. acf/validate_attachment/key={$field_key} – filter for a specific field based on itโ€™s key

This example will validate the file name of all attachments. If the attachment’s file name does not begin with the string ‘acf-‘, a message will be returned and displayed causing the upload/selection to fail.

functions.php

add_filter('acf/validate_attachment', 'my_acf_validate_attachment', 10, 4);

function my_acf_validate_attachment( $errors, $file, $attachment, $field ){
	
	if( substr($attachment['name'], 0, 4) !== 'acf-' ) {
		
		$errors[] = 'File name must begin with "acf-"';
		
	}
	
	
	// return
	return $errors;
	
}

 

Save

Save

Save

Related