解析WordPress中的post_class与get_post_class函数
post_class()
post_class是WordPress内置的一个用于显示文章class名称的函数,该函数通常会为每一篇文章生成独一无二的clss值,如果你需要制作你自己的主题,而且还需要一点个性的话,那你最好驻足一下,使用该函数并配合灵活的css代码,我们可以制作出个性化十足的WordPress博客。
post_class函数描述
该函数通常会为每一篇文章生成独一无二的clss值,可以很方便使用于文章所在的节点中。
函数使用
向其他的诸如header_image、wp_title这样的WordPress标签函数一样,不带get的函数通常是会直接显示出来而不返回任何值。
<postid="post-<?phpthe_ID();?>"<?phppost_class();?>><?phpthe_content;?></post>
是的,也许你已经注意到了,使用post_class函数时我们甚至不需要这样去写clss=“post_class()”;。
实例结果
不卖关子,结果如下
<postid="post-888"class="post-888posttype-poststatus-publishformat-standardhentrycategory-2tag-wordpress">文章内容</post>
以使用为主的函数讲完了,
下面照旧给出函数源代码:
想要了解更多关于该函数,以及get_post_class函数请关注后期文章。
/** *Displaytheclassesforthepostdiv. * *@since2.7.0 * *@paramstring|array$classOneormoreclassestoaddtotheclasslist. *@paramint$post_idAnoptionalpostID. */ functionpost_class($class='',$post_id=null){ //Separatesclasseswithasinglespace,collatesclassesforpostDIV echo'class="'.join('',get_post_class($class,$post_id)).'"'; }
get_post_class详解
get_post_class是post_class函数的基本实现,在WordPress中其他一些带get的函数一样,该函数将会有一个返回值,而该返回值将是一个包含当前文章基本信息的数组,get_post_class函数主要用来给每篇文章生成独一无为的class值而被封装出来的。
如果你是一个要求不高的人的话,那么post_class这个函数其实已经足够你折腾了。如果你是一个有着精神洁癖的人,不想自己的WordPress网站有太多无用代码的话,那你可以继续往下看。
get_post_class函数详解
该函数主要用来生成一个当前文章相关信息的数组,该数组所含信息我们往往用来作为文章层中的class值。
就像我上面提到的post_class函数,就是利用了本函数生成的class值。
并且该函数支持插入你自己的class值,一合并到返回数组中。
以上是我本人的理解,当然你也可以看一下官方的手册。
比较费解的手册内容如下:
WordPressThemeshaveatemplatetagforthepostHMTLtagwhichwillhelpthemeauthorstostylemoreeffectivelywithCSS.TheTemplateTagiscalledget_post_class.Thisfunctionreturnsdifferentpostcontainerclasseswhichcanbeadded,typically,intheindex.php,single.php,andothertemplatefilesfeaturingpostcontent,typicallyintheHTML
tag.
函数用法
<?phpget_post_class($class,$post_id);?>
如果在循环中,并且不需要插入自定义class值的话,该函数可不接受任何参数。
函数参数
$class:自定义class值,可以使字符串也可以死数组。
$post_id:文章ID
使用实例
$MyClass=get_post_class(); var_dump($MyClass);
输出结果:
array(9){ [0]=> string(8)"post-249" [1]=> string(4)"post" [2]=> string(9)"type-post" [3]=> string(14)"status-publish" [4]=> string(15)"format-standard" [5]=> string(6)"hentry" [6]=> string(18)"category-catcatcat" [7]=> string(8)"tag-tag1" [8]=> string(8)"tag-tag2" }
进阶实例
$MyClass=get_post_class('index-post',249); //或 $MyClass=get_post_class(array('index-post'),249); var_dump($MyClass);
输出结果:
array(10){ [0]=> string(8)"post-249" [1]=> string(4)"post" [2]=> string(9)"type-post" [3]=> string(14)"status-publish" [4]=> string(15)"format-standard" [5]=> string(6)"hentry" [6]=> string(18)"category-catcatcat" [7]=> string(8)"tag-tag1" [8]=> string(8)"tag-tag2" [9]=> string(10)"index-post" }
总结
根据函数的源代码,我们可以看出,本函数class值罗列的顺序为:
- 文章id
- 文章类型(页面、文章)
- 文章类型(页面、文章)与上一条相同,但结果中多了‘type-'字样
- 发布状态
- 文章格式
- 是否需要密码
- 文章所述分类(会逐个罗列所述分类)
- 文章所述标签(会逐个罗列标签)