Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
December 19, 2016

A fantastic way to allow searching by ID for Advanced Custom Fields objects

Nick
Nick
A fantastic way to allow searching by ID for Advanced Custom Fields objects

Advanced Custom Fields are awesome. They allow you to add an infinite amount of customizations to your WordPress site and are pretty easy to implement. They also have a large amount of hooks and filters you can use to enhance the fields as well.

One of the things I’ve had requested quite a bit by clients is to be able to search for a post by the ID associated with it. Say you have a select ACF field that loads all blog posts on your site. By default, ACF implements the Select2 dynamic dropdown so that it only populates a few and allows for live searching as you type. What if you have many posts that are similarly named and the only real unique thing about them is the ID? Typing in the ID will not bring up the post you desire by default. You need to add a short snippet of code to your functions.php file:

add_filter('acf/fields/post_object/query', 'pk_acf_ID_search', 10, 3);
function pk_acf_ID_search( $args, $field, $post_id ) {
   $search = !empty($args['s']) ? $args['s'] : false;
   if($search && is_numeric($search)){
      $args['post__in'] = array($search);
	  unset($args['s']);
      }
   return $args; 
}

This hooks in to the post_object field type specifically ( you can change that other field types as well ) and checks to see if what you are typing is numeric. This makes the assumption that if you are typing in a number then you are searching for an ID. If it is indeed a number then it adds an additional parameter to the query that is running for the search that checks if there is an exact match to the ID entered. If a match is found, it will return the corresponding post!

Nick Kalscheur

Nick Kalscheur

Lead Developer