Skip to content

Snippet: Assign Custom Card Templates Based on the Term (Category/Tag)

This snippet can be used with custom card templates (will not work with standard card styles - I will update the snippet after the 6.1 update to use a new filter to support any card style). The purpose of this code is so you can display a grid of posts but have each entry look different based on the term it's assigned to (primary category). This code relies on the setting available when editing any term that allows you to select a specific card style for that term.

/**
 * Apply the custom defined term card style to all entries (not just archives).
 */
add_filter( 'wpex_card_template_id', function( $template_id, $card ) {
	if ( ! empty( $card->post_id ) && function_exists( 'totaltheme_get_post_primary_term' ) ) {
		$primary_term = totaltheme_get_post_primary_term( $card->post_id );
		if ( ! empty( $primary_term->term_id ) ) {
			$primary_term_card_template = get_term_meta( $primary_term->term_id, 'wpex_entry_card_style', true );
			if ( $primary_term_card_template ) {
				$template_id = str_replace( 'template_', '', $primary_term_card_template );
				// This is for multi-language plugins like WPML omit if not needed
				if ( function_exists( 'wpex_parse_obj_id' ) ) {
					$template_id = wpex_parse_obj_id( $template_id );
				}
			}
		}
	}
	return $template_id;
}, 10, 2 );
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top