get_post_class()动态获取一个文章/页面的class类名称

目录

描述

Retrieve the classes for the post div as an array.

Many class names can be added to posts. For example, if the post is a sticky, then the 'sticky' class name is added. The class 'hentry' is always added to each post. For each category, the class that will be added is 'category-' with the category slug is added. The tags are the same way as the categories with 'tag-' before the tag slug. All classes are passed through the filter 'post_class' with the list of classes, followed by $class parameter value, with the post ID as the last parameter.

Note

get_post_class() is not simply a non-echoing alternative to post_class(). get_post_class() does not return a string, but an array that must be processed to produce text similar to what is echoed by post_class().

get_post_class() 描述

用法

<?php get_post_class($class$post_id); ?>

get_post_class() 用法

参数

$class

(string or array) (可选) A string or array of classes to add to the return value

默认值: '' (empty string)

$post_id

(int) (可选) An optional post ID

默认值: null

get_post_class() 参数

示例

Default

Default example without params and global $post object available (or in the loop).

With params

Passing an array of your own classes.


<?php
/* Optional:
global $post;
$postID = $post->ID;
 OR $postID = get_the_ID();
$postClass = get_post_class(array('my-class'));
 OR $postClass = get_post_class(array('my-class'), (int) $postID);
*/

$postClass get_post_class(array('my-class'));
var_dump($postClass);

/* Output:
array
  0 => string 'post-[ID]' (length=7)
  1 => string '[post_type]' (length=4)
  2 => string 'type-[post_type]' (length=9)
  3 => string 'status-[post_status]' (length=14)
  4 => string 'format-[post_format]' (length=15)
  5 => string 'hentry' (length=6)
  6 => string 'category-[...]'
  ...
  X => string 'tag-[...]'
  ...
  X+1 => string 'my-class' (length=8)
...
*/
?>

get_post_class() 示例

相关