Using WordPress ‘get_post_class()’ PHP function

The get_post_class() WordPress PHP function retrieves an array of the class names for the post container element.

Usage

get_post_class( $css_class = '', $post = null );

Example:

Input:

get_post_class( 'my-custom-class', 42 );

Output:

Array (
  [0] => post-42,
  [1] => post,
  [2] => type-post,
  [3] => status-publish,
  [4] => format-standard,
  [5] => hentry,
  [6] => category-example,
  [7] => tag-sample,
  [8] => my-custom-class
)

Parameters

  • $css_class (string|string[]): Optional. Space-separated string or array of class names to add to the class list. Default: ”
  • $post (int|WP_Post): Optional. Post ID or post object. Default: null

More information

See WordPress Developer Resources: get_post_class

Examples

Basic usage in a loop

Explanation: Display the class names in an article tag while in the loop.

// In the loop
$classes = get_post_class();
echo '<article class="' . esc_attr( implode( ' ', $classes ) ) . '" itemscope itemtype="http://schema.org/Article">';

Adding a custom class

Explanation: Add a custom class ‘my-custom-class’ to the post container element.

$classes = get_post_class( 'my-custom-class' );
echo '<article class="' . esc_attr( implode( ' ', $classes ) ) . '" itemscope itemtype="http://schema.org/Article">';

Adding multiple custom classes

Explanation: Add multiple custom classes ‘my-class-1’ and ‘my-class-2’ to the post container element.

$classes = get_post_class( array( 'my-class-1', 'my-class-2' ) );
echo '<article class="' . esc_attr( implode( ' ', $classes ) ) . '" itemscope itemtype="http://schema.org/Article">';

Getting classes for a specific post

Explanation: Retrieve the class names for a specific post with ID 42 and add a custom class ‘my-custom-class’.

$classes = get_post_class( 'my-custom-class', 42 );
echo '<article class="' . esc_attr( implode( ' ', $classes ) ) . '" itemscope itemtype="http://schema.org/Article">';

Display classes for a custom post type

Explanation: Retrieve and display the class names for a custom post type ‘my_custom_post_type’.

// In the loop for custom post type 'my_custom_post_type'
$classes = get_post_class();
echo '<article class="' . esc_attr( implode( ' ', $classes ) ) . '" itemscope itemtype="http://schema.org/Article">';