Products
GG网络技术分享 2025-03-18 16:13 0
我制作WordPress分类图片的原因是做分类页面的banner图,如果分类很多,那么希望分类与图片做一个一一对应的关系,这样就不用再用php做判断或者css去单独写样式。
首先获取到当前分类:get_the_category()。
foreach( get_the_category() as $cat) {
var_dump($cat);
}
var_dump($cat)可以将当前分类的数据输出,这里我们只取分类的ID即可:$cat_ID = $cat->cat_ID,用来拼接banner图片的名称:banner-ID.webp。
示例代码:
<?php
foreach( get_the_category() as $cat) {
$cat_ID = $cat->cat_ID;
?>
<div class="banner-<?php echo $cat_ID;?> position-relative">
<div class="text-end">
<img src="<?php echo get_template_directory_uri();?>/dist/images/banner-<?php echo $cat_ID;?>.webp" alt="<?php single_cat_title();?>">
</div>
</div>
<?php }?>在我们开发Wordpress主题的时候,我们会希望子分类继续使用父分类的页面模板,这样能大大减少我们的工作量。
那么WordPress子分类页面如何使用父页面模板呢?
这篇Wordpress教程详细为你解答。
//WordPress子分类页面使用父页面模板add_filter(\\\'category_template\\\', \\\'f_category_template\\\');function f_category_template($template){$category = get_queried_object();if($category->parent !=\\\'0\\\'){while($category->parent !=\\\'0\\\'){$category = get_category($category->parent);}}$templates = array(); if ( $category ) {$templates[] = \\\"category-{$category->slug}.php\\\";$templates[] = \\\"category-{$category->term_id}.php\\\";}$templates[] = \\\'category.php\\\';return locate_template( $templates );}
将上面代码复制到主题的functions.php页面即可。
扫码关注wpwp自学笔记
精选优质免费WordPress主题模板,分享最新WordPress实用建站教程!
记住我们的网址:ztJun.com
Demand feedback