Skip to Main Content

Linking to pages or posts in WordPress is easy but, linking to an uploaded PDF is cumbersome. Here’s a little script that allows you to link to uploaded PDFs (or other media) in the exact same way you would “link to existing content.”

The “traditional” route for linking to an uploaded PDF is confusing, especially for non-tech-savvy clients.

The JDM Digital nerds, with help from core WordPress contributors, put together this little script which adds Media to the “Link to Existing Content” modal in the TinyMCE WYSIWYG editor–without a plugin.

JDM Easy Link PDFs

Add the following to your theme’s functions.php file.

// Add PDF Linking to Modal "Existing Content"
// Author: https://jdmdigital.co
if( !function_exists('jdm_easy_link_pdfs') && !function_exists('jdm_easy_link_pdf_filter') ) {
  add_filter( 'wp_link_query_args', 'jdm_easy_link_pdfs' );
  function jdm_easy_link_pdfs( $query ) {
    if(is_admin()) {
      $query['post_status'] = array('publish','inherit');
      return $query; // That returns the attachment url
    }
  }
  // Filter attachment URLs and replace with ACTUAL urls.
  function jdm_easy_link_pdf_filter( $results, $query ) {
    foreach ( $results as &$result ) {
      if ( 'Media' === $result['info'] ) {
        $result['permalink'] = wp_get_attachment_url( $result['ID'] );
      }
    }
    return $results;
  }
  add_filter( 'wp_link_query', 'jdm_easy_link_pdf_filter',10,2);
}//End if not Exists

There you have it.  Now links to “Media” will be returned along with Posts and Pages in the “Link to Existing Content” box from the WYSIWYG editor.

A Word of Caution

The script may also return links to content that is not set to ‘published’.  In other words, you can link to posts or pages that are set to draft or scheduled.

We think that’s a good thing, but fair warning.

Why Not a Plugin?

There are plugins out there that do things similar to this, but with just 21 lines of code (including comments), it seems silly to use a plugin.

Share the love:

Get the Email

Join 1000+ other subscribers. Only 1 digest email per month. We'll never share your address. Unsubscribe anytime. It won't hurt our feelings (much).

Preview Email