2026-04-02 23:12:36 +08:00

86 lines
2.4 KiB
Markdown

---
title: WordPress全部文章分类页面
createTime: 2021/09/30
tags:
- Wordpress
categories:
- 随记
---
1. 复制一个 page.php 为 catlist.php
```bash
cd usr/wordpress # 自己的WordPress目录
find . -name page.php # 找到自己主题对应的路径
cd YourThemePath
cp page.php catlist.php
```
2. 在 catlist.php 最前添加代码
```php
<?php
/*
Template Name: Category
*/
?>
```
3. 在 catlist.php 中找到`<?php the_content();?>`并在其后添加如下代码
```php
<?php
//获得顶级分类
$taxonomies=get_terms('category',array('hide_empty'=>false,'parent'=>'0',));
if(!empty($taxonomies)){
foreach($taxonomies as $category){
if($category->name != '未分类'){?>
<h2><a href=<?php echo get_category_link($category->term_id)?>><?php echo $category->name?></a></h2>
<?php
echo '<ul>';
//获取二级分类
$cats=get_terms('category',array('hide_empty'=>false,'parent'=>$category->term_id,));
if(!empty($cats)){
foreach($cats as $cat){?>
<h3><a href=<?php echo get_category_link($cat->term_id)?>><?php echo $cat->name?></a></h3>
<?php
echo '<ul>';
//获取三级分类
$terms = get_terms('category',array('hide_empty'=>false,'parent'=>$cat->term_id,));
if(!empty($terms)) {
foreach($terms as $term){?>
<h4><a href=<?php echo get_category_link($term->term_id)?>><?php echo $term->name?></a></h4>
<?php
}
}
echo '</ul>';
}
}
echo '</ul>';
}
}
}
?>
<h2><a href="<?php echo home_url()?>/archives/category/uncategorized">未分类</a></h2>
<style>
h2>a,
h3>a,
h4>a {
color: black;
}
h2 {
margin-top: 2em;
font-size: 28px;
}
h3 {
font-size: 22px;
}
h4 {
font-size: 18px;
}
</style>
```
4. 保存模板,新建空白页面,页面模板选第二步 Template Name 后的名字,这里是 Category
5. 保存并发布,在菜单添加该页面即可