Is there a simple way to just insert a link to an image (without inserting an image)?

UPDATE 2018: The plugin listed below no longer works with WP (as of version 4.5 I believe) but the code listed in the accepted answer DOES still work, so use that instead.

UPDATE: just found this plugin which does what I wanted and more: https://wordpress.org/plugins/b09-link-to-existing-content/faq

I’m pulling my hair out with this, it seems so simple, but there is no easy way in WP (that I can find), and no plugin that will do the following:

In a post, I want to select some text, and then add a link to an existing (full size) image in my media library. I DON’T want to insert an image into my post.

The only way I have found to be able to do this is to find the image, copy the file link, then go to insert/edit url and paste it in. There should be a way to find it the same way you find pages or posts to link to in that same dialog. (OR maybe there is, and I simply can’t find it because I am an idiot.)

1
1

I found a solution based on the code of this page:
https://core.trac.wordpress.org/ticket/22180

All attachment files have a post status of ‘inherit’. So first you need to add “inherit” as one of the possible post status to search for. You can use the wp_link_query_args filter to do that.

function my_wp_link_query_args( $query ) {

     if (is_admin()){
          $query['post_status'] = array('publish','inherit');
     }

     return $query;

}

add_filter('wp_link_query_args', 'my_wp_link_query_args'); 

By default the url you would get would be the attachment url, and not the file url. So if you need the file url you can use the filter wp_link_query to filter the results.

function my_modify_link_query_results( $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', 'my_modify_link_query_results', 10, 2);

The foreach loops through all results, find the ones that have a type of Media, and replaces the attachment URL with the file url.

Leave a Comment