Skip to content

Snippet: Set Dynamic Template Based on Post Format

The following snippet can be used if you with to use a different dynamic template to be used for each post format. For example if you want to use a specific template when displaying Image posts then the globally set template.

/**
 * Filter the single post template to display a different template based on the current post format.
 *
 * @link https://total.wpexplorer.com/docs/snippets/set-dynamic-template-based-on-post-format/
 */
add_filter( 'wpex_singular_template_id', function( $template_id ) {
	if ( ! is_singular( 'post' ) ) {
		return $template_id;
	}

	$format = get_post_format();

	switch ( $format ) {
		case 'image':
			$template_id = 'IMAGE_TEMPLATE_ID';
			break;
		case 'video':
			$template_id = 'VIDEO_TEMPLATE_ID';
			break;
		case 'gallery':
			$template_id = 'IMAGE_TEMPLATE_ID';
			break;
		case 'quote':
			$template_id = 'QUOTE_TEMPLATE_ID';
			break;
		case 'audio':
			$template_id = 'AUDIO_TEMPLATE_ID';
			break;
		case 'link':
			$template_id = 'LINK_TEMPLATE_ID';
			break;
		default:
			$template_id = 'STANDARD_TEMPLATE_ID';
			break;
	}

	return $template_id;
} );
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