[+] Modify which posts are included in relationship form dropdowns to connect posts

In the UI it is possible to specify an author condition for the posts which are displayed in the dropdowns to connect posts in a relationship form, but there are no API functions to make any other modifications to the underlying queries which retrieve the posts.

But the following code demonstrates how it is possible to add additional query parameters. In the example, a form connects posts of the ‘left’ and ‘right’ post types, and in this case we modify the query for posts of the ‘right’ type to include a post meta condition that posts should have a value of ‘1’ for the ‘priority’ custom field.

add_action( 'wp_ajax_toolset_select2_suggest_posts_by_post_type', 'ts_mod_suggested_posts', 1 );
// if guest users can use your relationship form then uncomment the following line
// add_action( 'wp_ajax_nopriv_toolset_select2_suggest_posts_by_post_type', 'ts_mod_suggested_posts', 1 );
function ts_mod_suggested_posts(){

	add_action( 'pre_get_posts', 'ts_pre_get_posts' );
	function ts_pre_get_posts( $query ){
	
		if ( $query->query['post_type'] == 'left' )
		{
			// you can set additional query parameters for post type 'left' here

		} elseif ( $query->query['post_type'] == 'right' )
		{
			// you can set additional query parameters for post type 'right' here
			$query->set( 'meta_key', 'wpcf-priority' );
			$query->set( 'meta_value', '1' );
			$query->set( 'compare', '=' );
		}
	}
}

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments