Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save IAmAdamTaylor/81b92080dce7ba95fe2a10f96f69f124 to your computer and use it in GitHub Desktop.
Save IAmAdamTaylor/81b92080dce7ba95fe2a10f96f69f124 to your computer and use it in GitHub Desktop.
Show WordPress Media Attachments in Insert/Edit Link dialog
@IAmAdamTaylor
Copy link
Author

One of the things that's always annoyed me about WordPress's Insert Link dialog window is that you can't search for PDFs and other attachments in your media library. The workaround to upload the file to the Media Library, open it and copy-paste the URL has always felt clunky to me.

This plugin makes that issue go away by adding media attachments with specific extensions into that search window! It also works with ACF Link fields as they use the same Insert Link dialog.

By default only PDFs are shown, however you can filter this to include others such as .docx if needed.

To install

  1. Create a new file in /wp-content/mu-plugins/ and add the code from the Gist.
  2. Save the file.
  3. Done! Since the file was placed in mu-plugins WordPress will start using it straight away, no need to activate.

Filters

There are 2 filters available to use in this plugin:

smalg_allowed_extensions

Filter the list of file extensions that decide which media attachments are shown in the search dialog.
Defaults to: array('pdf')

When filtering, make sure to return an array and do not include the period before the extension, i.e. 'docx' instead of '.docx'.

/**
 * @param  array $extensions A list of file extensions to show in the search dialog.
 * @return array
 */
add_filter('smalg_allowed_extensions', 'gistiaat_smalg_allowed_extensions');
function gistiaat_smalg_allowed_extensions( $extensions ) {
    $extensions = array('pdf', 'docx');
    return $extensions;
} 

smalg_show_media_last

To keep the search dialog window clean, media attachments are shown last by default. You can use this filter to turn off that behaviour and show the search dialog list in newest to oldest posts order (the WordPress default).
Defaults to: true

// Use WordPress's quick return false function to disable it globally with one line...
add_filter('smalg_show_media_last', '__return_false');

// ... or use a separate function if you need fine grained control.

/**
 * @param  boolean $show_media_last True to show media attachments at the end of the search dialog list.
 * @return boolean
 */
add_filter('smalg_show_media_last', 'gistiaat_smalg_show_media_last');
function gistiaat_smalg_show_media_last( $show_media_last ) {
    // ... some condition
    return $show_media_last;
} 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment