Displaying an image on the category archive page

Each category page in WooCommerce looks the same, with of course the exception of the products in that category. This works great for a lot of merchants. However, some merchants like to differentiate their categories—maybe add a banner at the top of the category page to help users see at a glance what they're looking at, or some other customization.

By building on our knowledge of hooks from the preceding recipe, we can add an action onto an existing hook and display a category image.

Getting ready

You need at least one product and it needs to belong to a category. You should also have an image to represent that category.

How to do it…

In the following steps, we're going to start off with something really easy. WooCommerce allows you to upload an image for a category, but it doesn't display it anywhere by default. Once we get the image uploaded, then we can add some code to display it:

  1. From the WordPress admin, go to Products | Categories. You should see a list of categories as shown in the following screenshot:
    How to do it…
  2. Hover over any category and click on Edit.
  3. Click on Upload/Add Image.
  4. Then select a photo from your media library or add a new photo.
  5. Click on Update.

    We've added an image to a category. Now we need to write a function that will display that category image.

  6. In your code editor, open up your theme's functions.php file or a custom WooCommerce plugin.
  7. Add the following code to the bottom of the file:
    function woocommerce_cookbook_category_image() { 
        if ( is_product_category() ){ 
            global $wp_query; 
            $cat = $wp_query->get_queried_object(); 
            $thumbnail_id = intval( get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true ) ); 
            $image = wp_get_attachment_url( $thumbnail_id ); 
            if ( $image ) { 
                echo '<img src="' . esc_url( $image ) . '" alt="" />'; 
            } 
        }

    We have a function to display the image, but we haven't told the function when to run. We need to add one more line to do this.

  8. Below the code we just added, add one more line:
    add_action( 'woocommerce_archive_description', 'woocommerce_cookbook_category_image', 2 );
  9. Save and upload the file.

You should now see the image on the category page, as shown in the following screenshot:

How to do it…

How it works…

This code uses the same hooks system that was discussed in the preceding recipe. The function is hooked in at the right time by using an action. The function checks to make sure we're on a category page, then it looks in the database for an image that's associated with the category. If it finds one, it prints the image to the page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset