You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取子分类ID(寻求代码优化建议)

Hey there! Let's refactor your code to ditch those hardcoded category IDs and dynamically fetch child categories + their posts using the parent slug winners-2018—this will make your code way more maintainable and adaptable to future changes. Below's a step-by-step approach with example code (I'll assume you're working with WordPress since you mentioned categories/posts, but the logic translates to other CMS with similar category structures):

Step 1: Fetch the Parent Category by Slug

First, grab the parent category object using its slug instead of relying on a hardcoded ID. This lets you reference the category by its human-readable name, which is less likely to change.

Step 2: Get All Child Categories

Use the parent category's ID to pull all its direct child categories dynamically. No more manually adding IDs when new child categories are created.

Step 3: Iterate Over Child Categories & Fetch Their Posts

Loop through each child category, then pull all associated posts for each one. This keeps your code dynamic even as categories/posts are added or removed.

Example Code Implementation
// Define your parent category slug (no hardcoded IDs here!)
$parent_category_slug = 'winners-2018';

// Fetch the parent category object
$parent_category = get_category_by_slug($parent_category_slug);

// Handle case where parent category doesn't exist
if (!$parent_category) {
    echo '<p>Parent category "winners-2018" could not be found.</p>';
    return;
}

// Fetch all child categories of the parent
$child_categories = get_categories([
    'parent' => $parent_category->term_id,
    'hide_empty' => false, // Set to true if you want to skip categories with no posts
    'orderby' => 'name',
    'order' => 'ASC'
]);

// Check if there are any child categories to display
if (empty($child_categories)) {
    echo '<p>No child categories found under "winners-2018".</p>';
    return;
}

// Loop through each child category and its posts
foreach ($child_categories as $child_cat) {
    // Output child category header
    echo '<h2>' . esc_html($child_cat->name) . '</h2>';

    // Fetch posts for this child category
    $category_posts = get_posts([
        'category' => $child_cat->term_id,
        'posts_per_page' => -1, // Set to a number (e.g., 10) if you don't want all posts
        'orderby' => 'date',
        'order' => 'DESC'
    ]);

    // Display posts (or a message if none exist)
    if (!empty($category_posts)) {
        echo '<ul>';
        foreach ($category_posts as $post) {
            setup_postdata($post);
            echo '<li><a href="' . get_permalink($post) . '">' . get_the_title($post) . '</a></li>';
        }
        wp_reset_postdata(); // Reset post data to avoid conflicts
        echo '</ul>';
    } else {
        echo '<p>No posts found in this category.</p>';
    }
}
Key Optimizations & Notes
  • No hardcoded IDs: The entire flow relies on the parent slug, so you won't have to update code if category IDs change.
  • Error handling: We added checks for missing parent categories, empty child categories, and empty post lists to avoid broken UI.
  • Performance: If this code runs frequently, add caching (e.g., wp_cache_set/wp_cache_get for category/post data) to reduce database queries.
  • Flexibility: Adjust parameters like hide_empty, posts_per_page, or orderby to match your exact needs.

内容的提问来源于stack exchange,提问作者BoyIsBadNews

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:38:18