Problem: I would like to filter the parent post options in a Form that creates child posts. I would like to add custom code that filters the options based on their other post relationships.
Solution: Use the pre_get_posts filter to filter the parent post options in the parent post field. See the following example code:
/**
* Filter the Children parent field in the connect-toy-to-childmale Relationship Form
* to only show Children connected to Gender Male.
* https://toolset.com/forums/topic/filtering-posts-for-relationship-connection-in-a-submission-form/
*/
function filter_parent_posts( $query ){
$parent_post_type = "child"; // slug of parent post type
$child_post_type = "toy"; // slug of child post type
$rel_slug = "gender-child"; // slug of gender-child post relationship
$male_post_id = 9; // ID of Gender Male post
$rel_form_id = 26; // ID of the relationship form
// relationship form is on Toy single posts, queries parent_post_type posts
if ( ( defined('DOING_AJAX') && DOING_AJAX )
&& isset($query->query['post_type'][0])
&& $query->query['post_type'][0] == $parent_post_type
&& isset($_REQUEST['action'])
&& $_REQUEST['action'] == 'cred_association_form_ajax_role_find'
&& isset($_REQUEST['form_id'])
&& $_REQUEST['form_id'] == $rel_form_id
) {
// querying by gender post, which is parent in gender-child
$males = toolset_get_related_posts( $male_post_id, $rel_slug, array(
'query_by_role' => 'parent',
'limit' => 1000,
'offset' => 0,
'args' => array(),
'return' => 'post_id',
'role_to_return' => 'child'
));
$query->set( 'post__in', $males );
}
}
add_action( 'pre_get_posts', 'filter_parent_posts', 101, 1 );