If you are a fan of Advanced Custom Fields like me, then this little tidbit might be particularly useful to you.
Say you have 2 custom fields on a post: State and City. Each of those are custom post types that have many posts in them. States having 50, and cities having 10,000 from all over the USA. On this post you want to select a State and a City. The problem is that There are many duplicate city names in the United States – so when we go to select a city you won’t know which city belongs to which state. Yes, you could set up some ajax to only load cities of the selected State, but that is outside of this particular tidbit.
So… what do you do?
Turns out that smart guy Eliot Condon created a nice little filter for each of the ACF types. This one in particular is for the post_object ACF type.
1 2 3 4 5 | add_filter('acf/fields/post_object/result/key=field_57ffc0c52c69e', 'pk_acf_city_values', 10, 3); function pk_acf_city_values($title, $post, $field){ $state = get_post_meta($post->ID,'state',true); return $title.' - '.get_the_title($state); } |
So what this does is it cycles through each of the values of the ACF field and passes it through so you can filter it. So what we do here is find some meta data on the city that we added when importing the cities and then appending that to the actual title that you see when you select a the select2 dropdown. So now they read as “City – State”, such as “Dallas – Texas”. This helps make it it more clear what city you should be selecting!
Most, if not all, of the ACF field types have this type of filter – so the possibilities are endless