Possible to make the link autocompleter prioritize Tags before Posts?

After some digging I figured it out. We need to:

  • grab the editor settings
  • wrap the fetch link suggestions function in our own function
  • in this wrapper, we call the original, then do some sorting by type, in this case I changed it from ascending to descending so that tags comes before post
  • update the editor settings with the replacement function

You still need to put this on the appropriate JS hook/promise so it runs once the block editor is loaded such as wp.domReady(... ), and enqueue it so it only runs on the post/page editor, but this is the code for the difficult part:

const oldSettings = wp.data.select('core/block-editor').getSettings();
const sortedSuggest = async (
    search,
    searchOptions = {}
) => {
    const promise = oldSettings.__experimentalFetchLinkSuggestions( search, searchOptions );
    return promise.then( results => {
        results.sort( ( a, b ) => (a.type < b.type ) ? 1: -1 );
        return results;
    } );
};

const newsettings = {
    ...oldSettings,
    __experimentalFetchLinkSuggestions: sortedSuggest
}
wp.data.dispatch('core/block-editor').updateSettings( newsettings );

You can test this by copy pasting it into the browser dev console when the post editor is open, and searching.

enter image description here

Now that you have this, you should be able to modify the sortedSuggest function to change the sorting however you want, or even add/remove suggestions.

This is the structure it expects for each search result in the results array as defined by typescript:

/**
 * @typedef WPLinkSearchResult
 *
 * @property {number} id     Post or term id.
 * @property {string} url    Link url.
 * @property {string} title  Title of the link.
 * @property {string} type   The taxonomy or post type slug or type URL.
 * @property {WPKind} [kind] Link kind of post-type or taxonomy
 */

e.g.

[
    {
        "id": 298,
        "url": "https://frontenberg.tomjn.com/tag/welcome/",
        "title": "Welcome",
        "type": "post_tag",
        "kind": "taxonomy"
    },
    {
        "id": 1,
        "url": "https://frontenberg.tomjn.com/2017/11/04/hello-world/",
        "title": "Welcome to the Block Editor",
        "type": "post",
        "kind": "post-type"
    }
]