In my WordPress theme, I have a custom post type named Segments which contains two custom fields made with ACF. What I’m trying to achieve is have the second field’s search based on the first field’s value.
The first one is called emission, the type of the field is a taxonomy which links the Segment post to the emission taxonomy.
The second one is called episode, the type of the field is a post_object which links the Segment post to the episode post type.
Now, what I want is the second field, to filter the episodes, that are in the same emission as the selected value of the first field.
The problem I’m having is, I’m unable to get the value of the first field without saving the Segment. Here’s what I’ve tried:
add_filter('acf/fields/post_object/query/key=field_57503ed5193d6', array($this, 'show_episodes'), 10, 3);
/*
* Function to show episodes that are from the same program as the current segment.
*/
public function show_episodes($args, $field, $post_id){
error_log('Post Id: ' . $post_id);
error_log(json_encode(get_field_object('emission')));
error_log(json_encode(get_field('emission', $post_id)));
return $args;
}
When I’m calling this for an already saved Segment, it’s returning the saved emission value, which is logical because it’s the value saved in the Database. When I’m calling this for a new segment, it’s not working since it has no value saved in the database, therefore, it returns a null
. And whenever I edit the emission value for a saved segment, it still returns the old emission value (the one from the database).
I’ve been able to achieve the result using Ajax and PHP sessions. Here’s what I did:
Javascript
PHP
So when we receive the action
filter_episodes
via Ajax, it calls the PHP functionupdate_filter_episodes
.The startSession function to is check if the session has already been started:
And to update the query called by ACF, we need another hook which will call the function
show_episodes
:Not sure if this is the easiest way, but it works for me. However, feel free to let me know if someone has a better solution!