Advertisement

Advanced Use of Attachments in WordPress: Creating a 'Featured Image' for a Category

by

This tutorial is the final part of a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options.

In this series, I cover:

  • assigning categories and taxonomies to attachments,
  • querying media files by taxonomy so you can output them in a custom loop,
  • using taxonomy queries for images to display them on archive pages,
  • adding an image to a category or taxonomy term as the category or term's 'featured image'

In Part 1, I demonstrated how to create new taxonomies for attachments. In Part 2, I showed you how to create a custom template file for documents and add a loop which displays a link to the media file for each document, and in Part 3, I created a custom template file for the gallery-category taxonomy, which displays all images with a given term as a gallery-style archive page.

In this final part I'll demonstrate something slightly different: How to assign a category to an image and then edit the archive template for categories to display that image as the 'featured image' for that category. You could do this for tags or taxonomy terms too using very similar techniques.

For this tutorial I'm going to create a theme which will be a child theme of twenty fourteen. The theme will include a functions file and a custom template file for category archives. You can download this theme in the code bundle.

What You'll Need

To follow this tutorial you'll need the following:

  • a development installation of WordPress
  • FTP access (or MAMP or similar if you're working locally)
  • a code editor

1. Applying the Category to Attachments

By default, WordPress doesn't let you assign categories and tags to attachments, which you'll need to be able to do for this tutorial. Luckily it's easy fixed, as I demonstrated in an earlier tutorial on assigning categories and tags to attachments.

Note: This technique works for tags and categories  If you're doing this with your own taxonomies, you need to specify attachments as a post type the taxonomy applies to when you register it. You can do this by following the first part of this series.

In your theme, create a file called functions.php and add the following code to it:

<?php  
// add categories to attachments  
function wptp_add_categories_to_attachments() {
      register_taxonomy_for_object_type( 'category', 'attachment' );  
}  
add_action( 'init' , 'wptp_add_categories_to_attachments' ); 
?>

This uses the register_taxonomy_for_object_type() function to add categories to attachments. Now when you view the Media Library screen you'll see that categories are enabled.

The next step is to add some images - just one for each category. You also need to add another category called 'Featured' and make sure each image you want to use in this way is in that category too.

Below you can see an example media editing screen with the categories displayed:

advanced-use-of-attachments-in-wordpress-part4-image-with-categories

And you can also see all of my images with the correct categories assigned:

advanced-use-of-attachments-in-wordpress-part4-media-library-with-categories

Finally, I'll add some dummy posts to my site and put them in the relevant categories so that there's something to display in my archive page:

advanced-use-of-attachments-in-wordpress-part4-posts-with-categories

2. Creating the Category Template

The next step is to create the custom category template. As my theme is a child theme of twentyfourteen, I'll make a copy of that theme's category.php file and copy it to my child theme, with some changes to the opening comments:

<?php  
/**   
 * The template for displaying Category pages   
 * Custom template which displays a featured image first.   
 * Supports Part 4 of tutorial series on Advanced Use of Images in WordPress for WPTutsplus   
 */ get_header();  ?>
<section class="content-area" id="primary">
  <div class="site-content" id="content" role="main"><?php if ( have_posts() ) : ?>
    <header class="archive-header">
      <h1 class="archive-title"></h1>
        <?php 
          // Show an optional term description.
          $term_description = term_description();
          if ( ! empty( $term_description ) ) :
            printf( '<div class="taxonomy-description">%s</div>', $term_description );
          endif;
        ?>
    </header><!-- .archive-header -->

<?php   
// Start the Loop. 					   
while ( have_posts() ) : the_post(); 					     
      /* 					       
       * Include the post format-specific template for the content. If you want to 					            
       * use this in a child theme, then include a file called called content-___.php 					            
       * (where ___ is the post format) and that will be used instead. 					       
       */ 					     
      get_template_part( 'content', get_post_format() ); 					   
    endwhile; 			
		   
    // Previous/next page navigation. 					   
    twentyfourteen_paging_nav();			   
  else : 					     
    // If no content, include the "No posts found" template. 					              
    get_template_part( 'content', 'none' ); 				   
  endif;    
  ?></div><!-- #content -->
</section><!-- #primary -->

<?php  get_sidebar( 'content' ); get_sidebar(); get_footer(); ?>

3. Adding a Custom Query to the Category Template

Above the main loop, use WP_Query to add a custom loop. Insert the following after the closing </h1> tag:

<?php  
// display a featured image for the category  
// identify the current category  
$currentcat = get_queried_object(); 
$currentcatname = $currentcat->slug;
?>

This identifies the current category being displayed, using get_queried_object().

Below that, define the arguments for the custom query, using WP_Query:

<?php    
// define query arguments for the featured image    
$args = array( 	     
    'post_type' => 'attachment',
    'post_status' => 'inherit',
    'category_name' => $currentcatname,
  );
  $query = new WP_Query( $args );
?>

This identifies any attachments in the current category and also in the 'featured' category. Note that you need to include 'post_status' => 'inherit' as an argument because of the way WordPress sets post statuses for attachments.

Now below this, add the loop:

<?php  
  // The Loop  while ( $query->have_posts() ) : $query->the_post();
  // define attributes for image display
  $imgattr = array(
		'alt'   => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
	);

  // output the image ?>
  <div class="category-image"></div>
<?php 
endwhile;  
// reset the query so the default query can be run  
wp_reset_postdata(); ?>

Make sure you don't miss out wp_reset_postdata() at the end or the main query for the category archive won't work.

Having added all this, save your category template and view one of your category archive pages. It should look something like the screenshot at the beginning of this tutorial.

Summary

In this series of four tutorials I've demonstrated some advanced techniques for working with images in WordPress. These include:

  • Registering a taxonomy specifically for use with attachments
  • Creating a dosucmtn listing page using a custom template
  • Creating a gallery page to display images in a given cetageory, again using a custom template
  • Creating a 'featured image' for each category and displaying it on the category archive page.

As you've seen, you can do a lot more with images and media in WordPress than just attach them to posts or use them as featured images. With a bit of imagination, you can query them in the same way as any other post type and output links to documents or display images.

Advertisement