This tutorial is to show you a method for adding a custom icon image field to Post categories and displaying that icon before post titles that belong to that category. For it, I’ll be using the Advanced Custom Fields plugin and some custom code. The end result will look something like:
Register the Category Image/Icon Field
- Register a new fields group and call it something descriptive (i.e. “Category Fields”).
- In the Location section, under “Show this field group if”, select 1.) Taxonomy Term, 2.) is equal to, and 3.) category. This will make the fields available when adding/editing categories.
- Add a new field and call it Category Icon and ensure the key is category_icon. If you’re comfortable editing a little of the code below, you can make this whatever you’d like.
- Select Image as the field type and Image URL as the return value. Finally, make sure Library is set to “All”. None of the other options are very important so they can remain on the defaults.
- Check to make sure you now have the ability to upload an image to your categories.
Adding the Icon Before Post Titles
Next, we need to add the icon before the post titles and make sure that the post and icon are associated with the same category. The code below does the appropriate checks, pulls the first category of the post if it has multiple categories, gets the image belonging to that category and outputs it using the :before CSS pseudo-element. One important thing to note is that the images will output at their actual size so, to keep them small enough, make sure to use images with proper dimensions.