How to add a CSS class unique to the category of the carousel item in WordPress post carousel and WordPress custom post type carousel

Product: Wonder Carousel Version 18.4 or above

Level: Advanced

Tutorial:

You can use the Wonder Carousel plugin to easily create a WordPress post carousel or WordPress custom post type carousel. This tutorial will guide you how to add a CSS class unique to the category of the item in the carousel.

Step 1 - Create a WordPress post carousel or WordPress custom post type carousel

In Wonder Carousel, step 1, you can click the Add WordPress Posts button and the Add WooCommerce / Custom Post Type button to add posts or custom post type posts. You can click the button multiple times to add multiple post categories or custom post types.

wordpress-post-carousel

Step 2 - Use WordPress filter to add CSS class to the carousel item

Wonder Carousel has a filter wonderplugin_carousel_modify_post_items and wonderplugin_carousel_modify_custom_post_items that you can use to add extra CSS classes.

You can add the following PHP code to the end of the functions.php file of your WordPress theme. The code gets the categories of the post, then add a CSS class amazingcarousel-item-CATEGORYSLUG to the carousel item. If the post belongs to multiple categories, it will add all of them.

NOTE, modifying functions.php and adding PHP code may break your WordPress. Please backup your WordPress before making the change.

function add_css_to_post_carousel_item( $items ) {
	foreach($items as &$item)
	{
		if (isset($item->postid))
		{
			$categories = get_the_category($item->postid);
			if (!empty($categories))
			{
				$item->extracss = "";
				foreach($categories as $category)
				{
					$item->extracss .= " amazingcarousel-item-" . $category->slug;
				}
			}
		}
	}
    return $items;
}

Add the following code if you create a WordPress post carousel:

add_filter( 'wonderplugin_carousel_modify_post_items', 'add_css_to_post_carousel_item', 10, 3 );

And add the following code if you create a WordPress custom post type carousel:

add_filter( 'wonderplugin_carousel_modify_custom_post_items', 'add_css_to_post_carousel_item', 10, 3 );

An online demo is as follows:

If you use Google Chrome Developer Tools to inspect the HTML elements, you will find the extra CSS classes added by the code. You can then customise the carousel item by using your own CSS code.

wordpress-carousel-css