WordPress search attachments images by tags and categories
Posted on by ChandanIn this article, We will discuss how to make a WordPress custom image search based on their tags and categories. This is solution for them who want to make a custom search for attachments images.

WordPress, doesn’t provide taxonomies in media items by default. So, you have to add a plugin Attachment Taxonomies for it. Then you can associate the images by tags and categories. Also you can create different taxonomies as well from this plugin. This plugin makes our task easy.
First of all, we will create a page template, where we will perform the search. Here we add the form with a text input and a submit button. But we don’t use the form’s default behavior , but we handle this by Admin ajax.

Here is the Search template code , you can copy and paste it to your template:
<?php
/* Template Name: Search page
*
*
*
*/
?>
<?php get_header(); ?>
<div class="container">
<h1><?php the_title(); ?></h1>
<div class="form_container">
<div class="form-one-row">
<form>
<input id="text_sr" type="text" placeholder="enter image tags or categories to search">
<input type="submit" value="Submit" name="submit" id="sub_sr">
</form>
</div>
</div>
<div class="search_res_aj">
<!-- here the results will be displayed. -->
</div>
</div>
<?php get_footer(); ?>
After adding template in your theme, you can assign this template to a page. Like this: Select search-page-template and update the page. Therefore, we will create a “image Search page” and associate this template to it.

Now we will jump to theme functions.php and some code to enqueue the scripts. Then we will Add a js file where we have specified our path. Its under js folder. The following function makes our script file available at front end, therefore it will handle the click event on the form submit.
We have done something similar here:
How to create WordPress like button without login/plugin
WordPress include tags, categories and taxonomies in search results
// Add the JS
function add_my_search_scripts() {
wp_enqueue_script( 'img-search', get_template_directory_uri() . '/js/image-search.js',
array('jquery'), '1.0.0', true );
wp_localize_script( 'img-search', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
'security' => wp_create_nonce( 'my-special-string' )
));
}
add_action( 'wp_enqueue_scripts', 'add_my_search_scripts' );
// The function that handles the AJAX request
In the javascript File ( image-search.js ) , which will handle the ajax calls to server, we will add the following code:
jQuery(document).ready(function($) {
$('#sub_sr').click(function(e){
e.preventDefault();
var search_term=$('#text_sr').val();
if(search_term==""){ return; }
var data = {
action: 'my_search_action',
security : MyAjax.security,
search: search_term
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.post(MyAjax.ajaxurl, data, function(response) {
$('.search_res_aj').html(response);
});
});
});
At last , we will see how the server handles the ajax calls and return appropriate data in the form of img. Therefore, we will jump back to functions.php and add the following :
function image_handle() {
check_ajax_referer( 'my-special-string', 'security' );
$search = trim(htmlspecialchars($_POST['search'])) ;
$icat= get_terms( array('taxonomy' => 'attachment_category','hide_empty' => true) );
$itag= get_terms( array('taxonomy' => 'attachment_tag','hide_empty' => true) );
$mcat=array();
$mtag=array();
foreach($icat as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}
foreach($itag as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}
$attach=array();
$mtag_attach=array();
$args1= array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'attachment_category',
'field' => 'term_id',
'terms' => $mcat
),
array(
'taxonomy' => 'attachment_tag',
'field' => 'term_id',
'terms' => $mtag
)
)
);
$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($attach,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {
}
//print_r($attach);
if(!empty($attach)){
foreach($attach as $id){
echo "<img src='".wp_get_attachment_url( $id )."'/>";
}
}
if(empty($attach)){ echo "<p style='color:red;'>No match</p>";}
//echo $search;
die(); // this is required to return a proper result
}
add_action( 'wp_ajax_my_search_action', 'image_handle' );
add_action( 'wp_ajax_nopriv_my_search_action', 'image_handle' );
Output:

Now, open your page where you have added the code and see the result.
[…] WordPress search attachments images by tags and categories […]