I'm building a stock photo page for my company where we upload all photos our staff created so that it can be used later. It shows the ID of the image by post->ID so that users can see it, note it and be useful later - just like any other stock photo website.

However, when I try to use the ID and searching it in the search field, nothing comes out. I'm using Search Everything plugin but it doesn't seem to do anything. All other search by ID plugins only work on posts, not attachments (images).

So is there any plugins out there that I can use or do I need to add a script in my functions.php?

  • I think you should use another plugin for your problem. Since i have found a plugin fulltextsearch.org that's not only search through posts but also search through attachments as well. I hope it solves your problem. – Powell Marsh Jul 14 '18 at 12:31

The WP_Query class can match IDs as well as search terms. An idea would be to use the pre_get_posts action to detect if the search term is numeric and, if it is, set the query to work with attachments while passing the search as the ID.

function wpse223307_allow_search_by_attachment_id( $query ) {

    //Only alter the query if we are in a search screen,...
    if( ! is_search() ) :

    //...the search term has been set...
    if( ! isset( $query->query_vars['s'] ) ) :

    $search_term = $query->query_vars['s'];

    //...and the search term is a number
    if( ! is_numeric( $search_term ) ) :

    //Set the post type and post status to work with attachments (assuming you want to exclude other post types in numeric searches)
    $query->set( 'post_type', array( 'attachment' ) );
    $query->set( 'post_status', array( 'inherit' ) );

    //Match the search term with the attachment's ID and remove it from the query
    $query->set( 'p', $search_term );
    $query->set( 's', '' );


add_action( 'pre_get_posts', 'wpse223307_allow_search_by_attachment_id');
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.