Tell us what you are trying to do?
I have a post form for a CPT Referral where I've added a dropdown for a post-relationship (post reference for another CPT called Clinics) field. The Clinics CPT has a taxonomy field where a Clinic can be a medical clinic or a chiropractor clinic. On the Referral Post form, the dropdown shows all the values/posts I've created for Clinics but I would like to filter that dropdown options by the taxonomy.
Thanks Minesh. The problem I see with the solution by Luo is that I already have a this application in production and there are thousands of referrals already made with the post-relationship dropdown, so changing to a generic field will cause problems.
So the hook 'cred_filter_field_before_add_to_form' can't be used to modify the dropdown options before displaying?
Where:
- Replace 9999 with the post/page ID where you added the form
- Replace student with your parent post type slug
- Replace employee-department with your taxonomy slug
- Replace dept-account with your taxonomy term slug
I hope above code will help you to resolve your issue.
This code worked nicely. I had to refactor a little to fit my exact scenario for example on my Form I have two dropdowns; one showing filter list by one term and another filtering by another term of the same taxonomy. So in addition to checking for $_REQUEST['action'] I also check if the $_REQUEST['slug'] is also present with the value the field slug. And I add the relevant term to the $taxquery. I also had to check if the $post was an object because on loading of the form, there were multiple calls to the backend via ajax and some didn't have the $post. Not sure if that is just my specific situation. Other than that rest of the code worked fine.
Thanks again for a quick and valuable solution!
My issue is resolved now. Thank you! Here is the code I used which was a slight modification to Minesh, just so it fit my example:
function filter_container_archive( $query ){
global $post;
$post_id=default_value; //on occasion the $post will be null and so we can set a default value
//check if the $post is not empty and is an Object
if ( !empty($post) && is_a($post, 'WP_Post') ) {
$post_id=$post->ID;
}
if (defined('DOING_AJAX') && DOING_AJAX && $post_id==20) {
//check for the action & slug to focus in on a specific dropdown if you have multiple dropdown in the form
if($_REQUEST['action']=='select2_potential_relationship_parents' && $_REQUEST['slug']=='slug_of_field'){
if($query->query['post_type'][0]=='post_type_of_parent'){
$taxquery = array( array(
'taxonomy' => 'taxonomy',
'field' => 'slug',
'terms' => array('taxonomy_term_value'),
'operator'=> 'IN' ));
$query->set( 'tax_query', $taxquery );
}
}
}
}
add_action( 'pre_get_posts', 'filter_container_archive', 101, 1 );