如何修改PHP代码仅输出文章的主分类名称
How to Output Only the Parent Category in WordPress
Got it! Your current code loops through every category assigned to the post—including both parent and child categories. To only display the top-level parent category (the one with no parent category), we just need to add a simple check to filter out child categories.
Modified Code
Here's the adjusted code, with added WordPress security best practices included:
<?php // Grab all categories assigned to the current post $categories = get_the_category(); // Make sure there are categories to work with if (!empty($categories)) { foreach ($categories as $category) { // Check if this is a top-level (parent) category (no parent ID) if ($category->parent === 0) { $cat_link = get_category_link($category->cat_ID); // Use esc_url() and esc_html() to prevent XSS vulnerabilities echo '<a href="' . esc_url($cat_link) . '">' . esc_html($category->name) . '</a>'; // Optional: Add a break here if you only want the first parent category // (useful if multiple parent categories are assigned to the post) break; } } } ?>
Key Changes Explained
- Parent Category Filter: The
$category->parent === 0condition targets only top-level categories—child categories will have a parent ID matching their parent category's ID, so they get skipped. - Security Improvements: I added
esc_url()for the category link andesc_html()for the category name. These are critical WordPress best practices to block cross-site scripting (XSS) attacks. - Optional Loop Break: If your posts might have multiple parent categories assigned, the
breakstops the loop after the first one. Remove it if you want to display all parent categories instead.
Bonus: Target the Manually Set "Primary" Category
If you use a theme/plugin that lets you select a primary category (the main one you want linked to the post), use this code to prioritize that category first:
<?php // Get the ID of the manually set primary category $primary_cat_id = get_post_meta(get_the_ID(), '_primary_category', true); if ($primary_cat_id) { // Fetch the primary category data $primary_category = get_category($primary_cat_id); $cat_link = get_category_link($primary_category->cat_ID); echo '<a href="' . esc_url($cat_link) . '">' . esc_html($primary_category->name) . '</a>'; } else { // Fallback to the first parent category if no primary is set $categories = get_the_category(); if (!empty($categories)) { foreach ($categories as $category) { if ($category->parent === 0) { $cat_link = get_category_link($category->cat_ID); echo '<a href="' . esc_url($cat_link) . '">' . esc_html($category->name) . '</a>'; break; } } } } ?>
This will show your selected primary category first, and fall back to a parent category if no primary is assigned.
内容的提问来源于stack exchange,提问作者Onur Aydeniz
相关产品推荐
相关产品推荐

