fbpx

How to Create Categories and Tags for Photos in WordPress


How to Create Categories and Tags for Photos in WordPress

It frequently happens that in a web project, we want a classification by categories and tags for the photos. Indeed, for example, in several instances, we had to create photo galleries that were grouped by category. In this article, we will explain how to add an option to create categories and tags for your photos on WordPress. You can then use your knowledge of PHP to make the selection to display to your users.

How do I proceed?

To create categories and tags for photos on WordPress, you can use custom taxonomies or the default category. For this, you have the choice between using a WordPress extension or custom programming. For example, we lean more towards custom development in that it avoids us from facing the constraints of plugins. Nevertheless, below are the details of the two options you have at your disposal.

Create categories and tags for photos on WordPress without a plugin

Here is a step-by-step guide to creating categories and tags for your photos:

1- Create custom taxonomies for categories and tags

a. In the WordPress dashboard, go to “Appearance” > “Theme Editor”.

b. To create a new custom taxonomy for photo categories, click “functions.php” to open the file and add the following code:


<?php 
function create_photo_categories_taxonomy() {
    $labels = array(
        'name' => _x('Catégories de photos', 'taxonomy general name'),
        'singular_name' => _x('Catégorie de photo', 'taxonomy singular name'),
        'search_items' => __('Chercher des catégories de photos'),
        'all_items' => __('Toutes les catégories de photos'),
        'parent_item' => __('Catégorie parente'),
        'parent_item_colon' => __('Catégorie parente:'),
        'edit_item' => __('Modifier la catégorie de photo'),
        'update_item' => __('Mettre à jour la catégorie de photo'),
        'add_new_item' => __('Ajouter une nouvelle catégorie de photo'),
        'new_item_name' => __('Nouveau nom de catégorie de photo'),
        'menu_name' => __('Catégories de photos'),
    );

    $args = array(
        'hierarchical' => true,
        'labels' => $labels,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'photo-category'),
    );

    register_taxonomy('photo_category', array('attachment'), $args);
}
add_action('init', 'create_photo_categories_taxonomy', 0);

c. Then, to create a custom taxonomy for photo labels, add the following code:


<?php 
function create_photo_tags_taxonomy() {
    $labels = array(
        'name' => _x('Étiquettes de photos', 'taxonomy general name'),
        'singular_name' => _x('Étiquette de photo', 'taxonomy singular name'),
        'search_items' => __('Chercher des étiquettes de photos'),
        'popular_items' => __('Étiquettes de photos populaires'),
        'all_items' => __('Toutes les étiquettes de photos'),
        'edit_item' => __('Modifier l\'étiquette de photo'),
        'update_item' => __('Mettre à jour l\'étiquette de photo'),
        'add_new_item' => __('Ajouter une nouvelle étiquette de photo'),
        'new_item_name' => __('Nouveau nom d\'étiquette de photo'),
        'separate_items_with_commas' => __('Séparer les étiquettes avec des virgules'),
        'add_or_remove_items' => __('Ajouter ou supprimer des étiquettes'),
        'choose_from_most_used' => __('Choisir parmi les étiquettes les plus utilisées'),
        'not_found' => __('Aucune étiquette de photo trouvée'),
        'menu_name' => __('Étiquettes de photos'),
    );

    $args = array(
        'hierarchical' => false,
        'labels' => $labels,
        'show_ui' => true,
         'show_admin_column' => true,
        'query_var' => true,
        'rewrite' => array('slug' => 'photo-tag'),
    );

    register_taxonomy('photo_tag', array('attachment'), $args);
}
add_action('init', 'create_photo_tags_taxonomy', 0);

2 – Add your categories and tags

Once you have added these codes in the “functions.php” file of your current theme, you will see two new tabs below Media:

  • Photo Categories
  • Photo tags

You can now click on these tabs to add your categories and tags. Alternatively, in the library tab, you have the option to add your data directly to the right of the photo.

3 – Adjust your PHP codes to consider categories and labels

The choice of the mode of functioning will usually depend on the need. Indeed, you may want to create a gallery of photos grouped by categories. Or, you may want to display certain photos on pages based on categories or tags. To achieve this, you need to adapt your code accordingly. For example, one of our projects has a section for a gallery of photos organized by category (see the photo below). For this project, we are using ACF Pro with the gallery option to add photos. So, we will then use the ACF documentation reference code in our PHP code to make the block dynamic. Our procedure is therefore as follows:

  • Create the categories required for the types of hairstyles (Haircuts, coloring, …)
  • Add photos to the Media tab
  • Assign categories to each photo
  • Go to the block tab and add the photos to our gallery.
  • Make a request in our PHP code to display categories that are not empty. Finally, a second request to display the photos of the gallery, add the corresponding categories

Example of gallery code filtered by categories.

We leave you below an example of PHP code for creating categories and tags for photos.


	<?php
$file = basename(__FILE__, '.php');
/**
 * contact Block Template.
 *
 * @param   array $block The block settings and attributes.
 * @param   string $content The block inner HTML (empty).
 * @param   bool $is_preview True during AJAX preview.
 * @param   (int|string) $post_id The post ID this block is saved to.
 */

// Create id attribute allowing for custom "anchor" value.
   if( isset( $block['data']['preview_main_slider'] )  && is_admin()) { 
			echo '<img src="'. $block['data']['preview_main_slider'] .'" style="width:100%; height:auto;">';
 } else { /* rendering in editor body */
$id = 'contact-' . $block['name'];
if( !empty($block['anchor']) ) {
    $id = $block['anchor'];
}

// Create class attribute allowing for custom "className" and "align" values.
$className = 'contact';
if( !empty($block['className']) ) {
    $className .= ' ' . $block['className'];
}
if( !empty($block['align']) ) {
    $className .= ' align' . $block['align'];
}

// Load values and handle defaults.

$title = get_field('title')?:'contact';
$galleries = psw_field('gallery', $file); 
?>
		<div class="section-full content-inner-2 our-portfolio">
			<div class="container">
				<div class="section-head text-black text-center m-b20">
					<h2 class="text-primary m-b10"><?php echo psw_field("title", $file);  ?></h2>
					<div class="dlab-separator-outer m-b0">
						<div class="dlab-separator text-primary style-icon"><i class="flaticon-spa text-primary"></i></div>
					</div>
					<p class="m-b0"><?php echo psw_field('sub_description', $file);  ?></p>
				</div>
				<div class="row">
					<div class="col-lg-12 col-md-12 col-sm-12">
					    
					    <?php 
					    
					    // Catgéries de photos non vide. 
					    
					    $terms = get_terms( array(
    'taxonomy' => 'photo_category',
    'hide_empty' => false,
) );

?>
						<div class="site-filters style1 clearfix center">
							<ul class="filters" data-toggle="buttons">
								<li data-filter="" class="btn active"><input type="radio"><a href="#"><span>All</span></a></li>
								<?php 
								if(!empty($terms) && !is_wp_error($terms)) {
								    foreach($terms as $term) {
								  ?>
								  	<li data-filter="<?php echo esc_attr($term->slug ); ?>" class="btn"><input type="radio"><a href="#"><span> <?php echo esc_html( $term->name ); ?></span></a></li>
								  <?php
								    }
								} ?>
							
							
							</ul>
						</div>
					</div>
				</div>
				<div class="clearfix">
					<ul id="masonry" class="portfolio-box dlab-gallery-listing gallery-grid-4 gallery row lightgallery">
					    <?php 
					    $gallery = get_field("whyus_gallery", 'option'); 
					    if(!empty($gallery)) {
					        foreach($gallery as $val) {
					            $image_attributes = wp_get_attachment_image_src($val, 'medium_large');
		                        $photo_categories = get_the_terms($val, 'photo_category' );
		                        $key = "";
                                 if(!empty($photo_categories) && !is_wp_error($photo_categories)) {
                                     foreach($photo_categories as $t) {
                                         $key .=" ".$t->slug;
                                     }
                                 }
					            ?>
					            <li class="<?php echo $key; ?> card-container col-lg-3 col-md-3 col-sm-3">
							<div class="dlab-box">
								<div class="dlab-media dlab-img-overlay9 dlab-img-effect zoom">
								    <?php 
								    			            if ( $image_attributes ) {
					                $img = $image_attributes[0]; 
					                $width = $image_attributes[1]; 
					                $height  = $image_attributes[2]; 
					                ?>
					                <img width="<?php echo $width;  ?>" height="<?php echo $height;  ?>" src="<?php echo $img;  ?>" alt="<?php echo get_field("whyus_title", "option");  ?>">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo $img;  ?>" data-src="<?php echo $img;  ?>" class="icon-bx-xs check-km" title="<?php echo get_field("whyus_title", "option");  ?>">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
					                <?php 
} else {
    ?>
    <img width="385" height="385" src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/image-1.jpg" alt="">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/thumb/pic1.jpg" data-src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-1.jpg" class="icon-bx-xs check-km" title="Image Title Come Here 1">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
    <?php 
} ?>
								
								</div>
							</div>
							<br/>
						</li>
					            <?php 
					        }
					    } else {
					      ?>
					     
						<li class="image-1 image-4 card-container col-lg-3 col-md-3 col-sm-3">
							<div class="dlab-box">
								<div class="dlab-media dlab-img-overlay9 dlab-img-effect zoom">
								<img width="385" height="385" src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/image-1.jpg" alt="">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/thumb/pic1.jpg" data-src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-1.jpg" class="icon-bx-xs check-km" title="Image Title Come Here 1">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
								</div>
							</div>
							<div class="dlab-box p-tb30 image-2">
								<div class="dlab-media dlab-img-overlay9 dlab-img-effect zoom">
								<img width="385" height="385" src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/image-2.jpg" alt="">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/thumb/pic2.jpg" data-src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-2.jpg" class="icon-bx-xs check-km" title="Image Title Come Here 1">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
								</div>
							</div>
						</li>
						<li class="image-2 card-container col-lg-6 col-md-6 col-sm-6">
							<div class="dlab-box m-b30">
								<div class="dlab-media dlab-img-overlay9 dlab-img-effect zoom">
								<img src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-3.jpg" alt="">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/thumb/pic3.jpg" data-src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-3.jpg" class="icon-bx-xs check-km" title="Image Title Come Here 1">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
								</div>
							</div>
						</li>
						<li class="image-3 image-4 card-container col-lg-3 col-md-3 col-sm-3">
							<div class="dlab-box m-b30">
								<div class="dlab-media dlab-img-overlay9 dlab-img-effect zoom">
								<img width="385" height="385" src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/image-4.jpg" alt="">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/thumb/pic4.jpg" data-src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-4.jpg" class="icon-bx-xs check-km" title="Image Title Come Here 1">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
								</div>
							</div>
							<div class="dlab-box">
								<div class="dlab-media dlab-img-overlay9 dlab-img-effect zoom">
								<img width="385" height="385" src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/image-5.jpg" alt="">
									<div class="overlay-bx">
										<div class="overlay-icon">
											<span data-exthumbimage="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/middle/thumb/pic5.jpg" data-src="<?php echo get_stylesheet_directory_uri().'/images/'; ?>gallery/image-5.jpg" class="icon-bx-xs check-km" title="Image Title Come Here 1">		
												<i class="ti-fullscreen"></i> 
											</span>
										</div>
									</div>
								</div>
							</div>
						</li>
						 <?php
					    }
					    ?>
					</ul>
				</div>
			</div>
		</div>
 <?php } ?>

The code above allowed us to obtain the following display.   It is important to recall that we used the ACF Pro together with some features we created as part of the project. Therefore, you need to pay attention to the process to better understand how it works.

Some WordPress plugins to filter photos by categories.

Here are some popular WordPress plugins for filtering photos by categories:

  1. Envira Gallery
  2. NextGEN Gallery
  3. Photo Gallery
  4. FooGallery
  5. Justified Image Grid

We also recommend that you search your library for extensions to understand how they work.

In conclusion

Creating a photo gallery with a filter by categories or tags can be relatively easy. If you have web development skills, you can opt for custom development. Otherwise, a plugin can help with this direction. If you would like to work with experts to help you with development, contact us. Moreover, you can visit our code repository to download some interesting examples.

Gilblas Ngunte Possi

Gilblas Ngunte Possi

Founder and Full-Stack Developer at Prositeweb.

My proficiency with modern tools and a keen analytical sense regarding information technology enable me to provide superior guidance in the development and implementation of your web solutions.

Gilblas Ngunte Possi

Gilblas
Typically replies within an hour

Gilblas
Hi there👋

How can I help you?
1:40
Chat with Us