In the post editor screen, a post relationships panel can be used to “Connect Existing” posts in a post relationship. Users must select from existing post titles using a select2.js custom select field. If you have several possible posts with similar names, it might not be obvious which post you should select. You might want to add some additional identifying information, like a custom field value or a related post title from another post relationship. You can use the posts_results hook to filter those post titles. The following code snippet shows how you might accomplish this.
/* -------------------------------------------------------- * FILTER POST TITLES IN CONNECT EXISTING SELECT2.JS FIELD * IN POST RELATIONSHIPS PANEL IN POST EDITOR SCREEN * Use posts_results hook to customize the post titles shown as options in the select2.js field * displayed when using the Connect Existing feature in post relationships panel of post editor screen * @$posts: array of post objects to be displayed in select2.js field * @$query: query that was used to fetch $posts results */ function ts_filter_connect_existing_titles( $posts, $query ){ $post_types = ['band', 'event']; // edit the slug(s) of post type(s) to modify $rel_slugs = ['band-event']; // edit the slug(s) of post relationship(s) where you want to modify titles // !! - You probably should not edit anything in these conditionals. skip to the foreach code to manipulate titles - !! // We only want to run this if User is searching for related content for specific relationships using the Connect Existing dialog if ( defined('DOING_AJAX') && isset($_REQUEST['action']) && $_REQUEST['action']=='types_related_content_action' && isset($_REQUEST['relationship_slug']) && in_array($_REQUEST['relationship_slug'], $rel_slugs) && isset($query->query['post_type'][0]) && in_array($query->query['post_type'][0], $post_types) ) { foreach($posts as $post){ // this loops over each WP Post object that will be included in select2.js options // modify the titles of each post here as desired $post->post_title = 'Test-' . $post->post_title; } } return $posts; } add_action( 'posts_results', 'ts_filter_connect_existing_titles', 99, 2 );
You can adjust the post type slugs band and event, as well as the post relationship slug band-event to match your content. This code will manipulate the titles of posts in any of the post types included in the $post_types array, in the Connect Existing dialog available for any of the post relationships included in the $rel_slugs array. Modify the post titles however you’d like in the foreach loop. Note that this does not extend search capabilities – i.e. you cannot search for the modified title. The modification only applies to the title displayed in the select2.js field options.
Support Thread Example
Let us know if this snippet is not working for you:
This snippet doesn’t work