星期三 , 22 1 月 2025

自定义分类单页模板

function category_single_template($single) {

    global $post;

    if (has_category('fuwu', $post)) {
        $single = get_template_directory() . '/single-fuwu.php'; 
    }
    return $single;

}
add_filter( 'single_template', 'category_single_template' );

直接在single.php 上判断分类加载模板

<?php
// Standard loop start, sets up the post
if (have_posts()) { 
  while (have_posts()) { 
    the_post();

    // Get the categories on this post as WP_Term objects
    $categories = get_the_category();
    
    // Check if post is in the news category
    $news_category = get_category_by_slug('news'); 
    if (in_array($news_category, $categories)) {
      // Load custom news single template
      get_template_part('partials/single', 'news');
    } 
    else {
      // Load default single template 
      get_template_part('partials/single');
    }
  }
} 
?>

或者直接用is_category判断

is_category( ‘fuwu’ );