get_post_class()
Gets CSS classes as an array that need to be used in the post for output in the HTML tag.
The final array of classes is passed through the filter post_class, use it when you need to change the displayed classes depending on different conditions.
To immediately output the classes on the screen as a string, use post_class()
Where and what classes are added
-
hentry,post-{$post_id},type-{$post_type},status-{$post_status},{$post_type}— are output for all posts. The parts in brackets are replaced with the corresponding variable of the current post;
{$post_type} is NOT output in the admin panel... -
sticky— if this is a sticky post, it is only displayed on the is_home() page. In the admin panel, it is displayed asstatus-sticky; -
has-post-thumbnail— if the post has a thumbnail; -
format-{post format}— if support for formats is enabled. If the format is not specified, it will outputformat-standard. -
post-password-required— for password-protected posts. {$taxonomy}-{$slug}— if the post belongs to a taxonomy. $taxonomy will be replaced with the name of the taxonomy, and $slug with the name of the term (element of the taxonomy). For example:category-blog;
The exception here is the taxonomypost_tagfor which the prefix will betag-, notpost_tag-. For example:tag-novosti.
Hooks from the function
Returns
String[]. An array in which the elements are the names of the classes.
Usage
get_post_class( $class, $post_id );
- $class(string/array)
- The classes that need to be added to the list.
Default: '' - $post_id(int/WP_Post)
- The ID or object of the post whose classes need to be obtained.
Default: null
Examples
#1 Output demonstration
$classes = get_post_class(); print_r( $classes ); /* Array ( [0] => post-219 [1] => post [2] => type-post [3] => status-publish [4] => format-standard [5] => has-post-thumbnail [6] => hentry [7] => category-blog [8] => tag-novosti ) */
#2 Let's output all classes as a string
This code can be used as a replacement for post_class():
<div class="<?= join( ' ', get_post_class() ) ?>">
#3 Adding our own classes
// as string $classes = get_post_class( 'foo bar' ); // or as array $classes = get_post_class( [ 'foo', 'bar' ] ); /* Both examples will add to the resulting array Array ( [0] => foo [1] => bar [2] => post-19 ) */
#4 Delete unnecessary class
Suppose we need to get rid of the class hentry, then use this filter before calling get_post_class() or post_class():
add_filter( 'post_class', 'remove_hentry' );
function remove_hentry( $classes ) {
$unset = array( 'hentry' ); // you can add more
return array_diff( $classes, $unset );
}
Notes
- Since version 3.1, support for post formats has been introduced.
- Since version 4.2, support for taxonomies has been introduced.
Changelog
| Since 2.7.0 | Introduced. |
| Since 4.2.0 | Custom taxonomy class names were added. |