Timeless
Published in

Timeless

Assigning custom images and colors to the WordPress post categories.

WordPress doesn't have a default option for assigning some images or colors as category meta and use it. I personally experienced that I needed an icon or image and wanted to have some unique colors for each category and use it in the front-end dynamically.

So, here we gonna know about some WordPress action hooks to create two input fields in the category edit page and store them in the database. Hooks are of two types in WordPress

  1. Action Hook
  2. Filter Hook

Hooks are nothing but, it hooks a function on to a specific action. edit_category_form_fields and edited_category are the two hooks we used to achieve it.

edit_category_form_fields is hooked to category_color_image_fields function where it checks, whether image or colors is already assigned to a category and get value from input fields.

edited_category is the WordPress Core edited category hook, hooked to save_category_meta_fields function where it, if checks the category meta input field values, store them in variables and update them in the database respective to the category id.

Your default category edit page will look like the below screenshot.

Default Category Edit Page.

Copy the above GitHub gist code to your theme functions.php, save the file now reload the same category edit page, you will get two extra input fields for image Url and color. And, it will look like the below screenshot.

Updated Category Edit Page.

Upload the desired image on media uploader and paste the image Url in the Category Image Url input field. And, copy the desired color Hex code on the category color input field, click on update to update them into the database.

Again to fetch and show them in front-end copy the below GitHub gist code and use them in category.php to show them.

get_query_var(‘cat’); get the category ID.

get_option(“category_$cat_id”); this gets the data stored in the database respective to the category ID provided.

Tada! The output you get with the above code for your category image and color.

Let me know if you have any issues, suggestions in the responses.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store