WordPress Custom Conditional Tags

Conditional Tags

WordPress’ Conditional Tags offer a lot of control over how content displays or functions queue in themes and page templates. Sometimes, though, they don’t quite make the grade. If you’re trying to write a function that controls a custom post type, for example, you might find the onboard system cumbersome. But that’s alright. We can step out of the box and register a Custom Conditional Tag in a snap to solve the problem in a secure, neat way. Just reference the WP Core file category-template.php (found in /wp-includes).

Checkout the function ‘has_term’ ( the last function as of WP 3.9.1 ).

/**
 * Check if the current post has any of given terms.
 *
 * The given terms are checked against the post's terms' term_ids, names and slugs.
 * Terms given as integers will only be checked against the post's terms' term_ids.
 * If no terms are given, determines if post has any terms.
 *
 * @since 3.1.0
 *
 * @param string|int|array $term Optional. The term name/term_id/slug or array of them to check for.
 * @param string $taxonomy Taxonomy name
 * @param int|object $post Optional. Post to check instead of the current post.
 * @return bool True if the current post has any of the given tags (or any tag, if no tag specified).
 */
function has_term( $term = '', $taxonomy = '', $post = null ) {
	$post = get_post($post);
	if ( !$post )
		return false;
	$r = is_object_in_term( $post->ID, $taxonomy, $term );
	if ( is_wp_error( $r ) )
		return false;
	return $r;
}

In the instance that a Custom Conditional Tag became valuable to me, I used custom post types and custom fields to display products on a Genesis Child Theme. Rather than use an array of out-of-the-box Conditional Tags to display price and inventory information, I simply used ‘has_product’.

To make it work, I simply duplicated ‘has_term’ function in my functions.php file and modified the parameters. In my case, that meant adding ‘product-category’, the slug for my custom post type, in the $taxonomy field, and changing the function slug from ‘has_term’ to ‘has_product’. Voila! Custom Conditional Tag.

/* CREATE has_custom CONDITIONAL FUNCTION FOR POST TYPES
Allows has_custom to be used as conditional tag. Checkout
category-template.php 'function has_term' as of WP 3.9.1
to expand or modify this function. Author James Valeii, 
Author URL boilingpotmedia.com.
---------------------------------------------- */
function has_product( $taxonomy = 'product-category', $taxonomy = '', $post = null) {
	$post = get_post($post);
	if ( !$post )
		return false;
	$r = is_object_in_term( $post->ID, $taxonomy );
	if ( is_wp_error( $r ) )
		return false;
	return $r;
	}

If you’re interested, I wrote a longer post that details how I registered my Custom Post Type, My Custom Taxonomy, and my Custom Fields, and the way that it all came together with Custom Conditional Tags to display Custom Fields in a Genesis Child theme.