Adding post template names to post_class()

For my currently work-in-progress-theme, I want to display posts with post templates different in the blog view. For that, I add the name of the post template to the post_class() output via the post_class filter. This post shows you how to get this working.

Function for returning the post template slug

Because I need the name of the post templates in various places of the theme, we write a function for returning the post template name first:

if ( ! function_exists( 'photographia_get_post_type_template' ) ) { /** * Returns the post type template slug * without templates/ dir and .php ending. * * @return string */ function photographia_get_post_type_template() { $template_slug = get_page_template_slug(); if ( '' !== $template_slug ) { /** * Remove »templates/« from slug. */ $template_slug = str_replace( 'templates/', '', $template_slug ); /** * Remove .php file ending. */ $post_type_template = str_replace( '.php', '', $template_slug ); return $post_type_template; } else { return ''; } } }
Code language: PHP (php)

At the first line, we check if the function photographia_get_post_type_template() was previously defined by a child theme (or plugin). Inside the function, we determine the current’s post template slug with get_page_template_slug(). If the post has no template, the function call returns an empty string. If the result is not empty, the theme’s template slugs look like that: templates/name-of-template.php. We do not need the templates/ part and the .php ending — let us remove them with two str_replace() calls and return the $post_type.

If the post has no template, we return an empty string.

Function for adding the class

Now the function, which filters the post_class:

/** * Add classes to post_class() * * @param array $classes array with post classes. * * @return array */ function photographia_filter_post_classes( $classes ) { /** * Get the post type template name. * Empty string if no template is used. */ $post_type_template = photographia_get_post_type_template(); /** * Add post template class if post has a template */ if ( '' !== $post_type_template ) { $classes[] .= "-$post_type_template-template"; } return $classes; } add_filter( 'post_class', 'photographia_filter_post_classes' );
Code language: PHP (php)

We get the string of the post template name — or an empty string if no template is used — by calling our photographia_get_post_type_template() function. If the function does not return an empty string, we add a new array value to $classes and return the classes array.

Now if a post has a template, calling the post_class() function in the loop returns a class with the pattern -templatename-template.

Leave a Reply

Your email address will not be published. Required fields are marked *