我的一个朋友前几天要求我编写Wordpress函数,以打印出类别列表以及这些类别中的所有帖子以及帖子中可能包含的所有元数据。
该功能所要做的就是获取类别列表,然后为每个类别获取与该类别关联的帖子列表。确实不多,但在某些情况下很有用。
function getCategoryPostList($args = array())
{
if (is_string($args)) {
parse_str($args, $args);
}
// 设置默认值。
$defaults = array(
'echo' => true,
);
// 将默认值与参数合并。
$options = array_merge($defaults, (array)$args);
$output = '';
// 获取顶级类别
$categories = get_categories(array('hierarchical' => 0));
// 遍历找到的类别。
foreach ($categories as $cat) {
// 打印出类别名称
$output .= '<p><strong>' . $cat->name . '</strong></p>';
// 获取与该类别相关的帖子
$tmpPosts = get_posts('category=' . $cat->cat_ID);
// 确保找到了一些帖子。
if (count($tmpPosts) > 0) {
$output .= '<div>';
// 循环浏览找到的每个帖子。
foreach ($tmpPosts as $post) {
// 获取发布元数据。
setup_postdata($post);
// 打印出帖子信息
$output .= '<p><a href="' . get_page_link($post->ID) . '" title="' . $post->post_title . '">' . $post->post_title . '</a></p>';
$output .= '<p>' . $post->post_excerpt . '</p>';
}
$output .= '</div>';
}
}
if ($options['echo'] == true) {
// 打印$output变量。
echo $output;
}
// 返回
return $output;
}要使用该功能,请将其弹出到functions.php文件中,然后按如下所示在您的主题中调用它:
getCategoryPostList();
如果您创建自定义页面模板并将函数调用放在其中,那么这可能会最好地工作。
此功能的唯一问题是,如果您有多个类别的帖子,那么您会发现该帖子出现了多次。对于我写的人来说,这不是问题,但是如果您要更改此内容并想出一种好的方法,请发表评论!