如何为自定义WordPress主题添加文章分类选项?
Got it, let's get this sorted for you! First, I spotted a couple of small typos in your existing code that could cause unexpected errors—let's fix those first, then add the category functionality you need.
Step 1: Fix Typos in Your Existing Code
Here are the critical corrections to avoid bugs:
'edt_item'should be'edit_item'(typo in the label key)'menu-icon'should be'menu_icon'(WordPress uses underscores for this parameter, not hyphens)- You were missing a closing parenthesis
)at the end of theregister_post_typecall
Step 2: Add Category Support (Two Flexible Options)
You have two solid paths to add category selection for your investing custom post type:
Option 1: Use WordPress's Default Category Taxonomy
If you want to reuse the default "Categories" system that comes with WordPress (so your investing posts share categories with regular posts), just add a taxonomies parameter to your register_post_type array. This attaches the existing category taxonomy to your custom posts.
Here's the updated full code:
function gt_custom_post_type() { register_post_type('investing', array( 'rewrite' => array('slug' => 'investing posts'), 'labels' => array( 'name' => 'Investing Posts', 'singular_name' => 'Investing Post', 'add_new_item' => 'Add New Investing Post', 'edit_item' => 'Edit Investing Post', // Fixed typo ), 'menu_icon' => 'dashicons-clipboard', // Fixed parameter name 'public' => true, 'has_archive' => true, 'supports' => array( 'title', 'thumbnail', 'editor', 'excerpt', 'comments' ), 'taxonomies' => array('category') // Add this line to enable default categories )); // Added missing closing parenthesis } add_action('init', 'gt_custom_post_type');
Option 2: Create a Custom Category Taxonomy (Tailored to Your Posts)
If you want a dedicated category system just for your Investing Posts (to keep your investing content organized separately from regular posts), register a custom taxonomy. This is ideal for niche content.
Add this additional function right after your existing gt_custom_post_type function:
function gt_investing_taxonomy() { register_taxonomy( 'investing_category', // Unique slug for your custom taxonomy 'investing', // Attach to your "investing" custom post type array( 'label' => 'Investing Categories', 'rewrite' => array('slug' => 'investing-categories'), 'hierarchical' => true, // Lets you create parent/child categories like default ones 'show_admin_column' => true, // Adds a dedicated column in the investing posts list ) ); } add_action('init', 'gt_investing_taxonomy');
How to Verify It Works
After updating your functions.php file:
- Refresh your WordPress admin dashboard
- When creating or editing an
Investing Post, you'll see a category selection box (either the default "Categories" or your new "Investing Categories") in the sidebar - You can manage these categories directly from the left-hand menu under the
Investing Postssection
内容的提问来源于stack exchange,提问作者Jeff S

