get_post_class()
Retrieves the classes for the post div as an array.
The class names are many. If the post is a sticky, then the 'sticky' class name. The class 'hentry' is always added to each post. If the post has a post thumbnail, 'has-post-thumbnail' is added as a class. For each taxonomy that the post belongs to, a class will be added of the format '{$taxonomy}-{$slug}' - eg 'category-foo' or 'my_custom_taxonomy-bar'.
The 'post_tag' taxonomy is a special case; the class has the 'tag-' prefix instead of 'post_tag-'. All class names are passed through the filter, post_class, with the list of class names, followed by $class parameter value, with the post ID as the last parameter.
Hooks from the function
Return
String[]
. Array of class names.
Usage
get_post_class( $class, $post_id );
- $class(string|string[])
- Space-separated string or array of class names to add to the class list.
Default: '' - $post_id(int|WP_Post)
- Post ID or post object.
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 ); }
Changelog
Since 2.7.0 | Introduced. |
Since 4.2.0 | Custom taxonomy class names were added. |