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:

  function( $args ) {
    $args['relevanssi'] = true;
    unset( $args['post_type'] );
    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:

  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,
    return $results;

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. Required fields are marked *