如何获取WordPress自定义文章类型的分类法、分类及标签?
Got it! Since you already know how to fetch custom fields using get_post_custom($post->ID), let's walk through the equivalent ways to pull taxonomies, categories, and tags for your custom post types—these are purpose-built functions that make this way easier than digging into the database directly.
If you want to see all taxonomies registered to a specific custom post type (like your portfolio or book CPT), use get_object_taxonomies():
global $post; // Replace 'your_custom_post_type' with your actual CPT slug $taxonomies = get_object_taxonomies( $post->post_type, 'objects' ); echo '<pre>'; // Prints full taxonomy objects (labels, settings, etc.) print_r( $taxonomies ); echo '</pre>';
If you just want the taxonomy slugs instead of full objects, swap the second parameter to 'names':
$taxonomy_slugs = get_object_taxonomies( $post->post_type, 'names' ); print_r( $taxonomy_slugs ); // Outputs something like array('category', 'post_tag', 'genre')
For the actual terms (categories, tags, or custom taxonomy terms) assigned to the current post, use get_the_terms(). This works for both default taxonomies (like category/post_tag) and your custom ones.
Example: Get Categories for the Post
global $post; $categories = get_the_terms( $post->ID, 'category' ); // Always check if we got valid results (not an error) if ( ! is_wp_error( $categories ) && $categories ) { echo '<pre>'; print_r( $categories ); // Shows all category objects assigned to the post echo '</pre>'; }
Example: Get Tags for the Post
Tags are just a default taxonomy with the slug post_tag, so use the same function:
global $post; $tags = get_the_terms( $post->ID, 'post_tag' ); if ( ! is_wp_error( $tags ) && $tags ) { print_r( $tags ); }
Example: Get Custom Taxonomy Terms
If you have a custom taxonomy like genre for a book CPT:
global $post; $genres = get_the_terms( $post->ID, 'genre' ); if ( ! is_wp_error( $genres ) && $genres ) { print_r( $genres ); }
If you need to pull all available terms in a taxonomy (not just those assigned to the current post), use get_terms():
// Replace 'genre' with your taxonomy slug $all_genres = get_terms( array( 'taxonomy' => 'genre', 'hide_empty' => false, // Set to true if you only want terms with posts ) ); if ( ! is_wp_error( $all_genres ) && $all_genres ) { print_r( $all_genres ); }
These functions are the direct equivalent of get_post_custom() but tailored for taxonomy data—no need to mess with $wpdb queries unless you have super specific needs. Let me know if you need help tweaking any of these for your use case!
内容的提问来源于stack exchange,提问作者JeVic

