Posted on

Using Relevanssi in wp_link_query

If you want to use Relevanssi in the link queries (the search you get when adding links to posts in Classic editor), that’s easy. Make sure Relevanssi is enabled in admin searches, and then add this function:

add_filter(
  'wp_link_query_args',
  function( $args ) {
    $args['relevanssi'] = true;
   return $args;
  }
);

This function will make the Classic Editor link queries use Relevanssi. This approach generally works fine, but if your search results include taxonomy terms or user profiles, there will be errors as the search will try to get the non-existing post type label. These errors are not dangerous.

Unfortunately, it’s much harder to make the Gutenberg link search use Relevanssi; please let me know if you know how to do that.

Multisite searches

We need to switch to the correct blog for multisite searches to get the permalinks right. For this, we need to rerun the whole query in the wp_link_query filter hook. The code is otherwise directly copied from the WP default code (in wp_link_query() in wp-includes/class-wp-editor.php), it just adds in the switch_to_blog() and restore_current_blog(). You can, of course, make any other changes to the results here as well:

add_filter(
  'wp_link_query',
  function( $results, $query ) {
    $get_posts           = new WP_Query();
    $query['relevanssi'] = true;
    $new_posts           = $get_posts->query( $query );
    $results             = array();
    foreach ( $new_posts as $post ) {
      switch_to_blog( $post->blog_id );
      if ( 'post' === $post->post_type ) {
        $info = mysql2date( __( 'Y/m/d' ), $post->post_date );
      } else {
        $info = $pts[ $post->post_type ]->labels->singular_name;
      }

      $results[] = array(
        'ID'        => $post->ID,
        'title'     => trim( esc_html( strip_tags( get_the_title( $post ) ) ) ),
        'permalink' => get_permalink( $post->ID ),
        'info'      => $info,
      );
      restore_current_blog();
    }
    
    return $results;
  },
  10,
  2
);

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published.