2
votes

I want to retrieve the data field that are being used in a custom post type, retrieve data like taxonomy, categories, tags. I am only familiar with retrieving custom fields in which I used this. What is the equivalent value for taxonomies, tags and categories?

global $post, $wpdb;
echo '<pre>';
 print_r( get_post_custom($post->ID) );
echo '</pre>';
1

1 Answers

0
votes

In the code below, you will get all taxonomies and custom taxonomies for the current $post object.

Note: To get the taxonomies (or custom-taxonomies), I am not using WordPress get_object_taxonomies() function as it will get all taxonomies for the post_type and not for the $post itself. Instead I use a very lighter SQL query, that will get only the taxonomies that are set for the current $post.

This code will display taxonomy label name with the coma separated terms, only if it's not empty.

global $post, $wpdb;

$taxonomies = $wpdb->get_col( "SELECT DISTINCT tt.taxonomy
FROM {$wpdb->prefix}term_taxonomy as tt
JOIN {$wpdb->prefix}term_relationships as tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tr.object_id = {$post->ID}" );

// Loop through all taxonomies for this WP_Post object
foreach ( $taxonomies as $taxonomy ) {
    // Get the WP_Term objects for this taxomnomy and this post ID
    $terms = wp_get_post_terms( $post->ID, $taxonomy );
    // If this taxonomy has terms for this post ID
    if( count($terms) > 0 ){
        $term_names = array();

        // Get the taxonomy label name
        $taxonomy_label_name = get_taxonomy( $taxonomy )->labels->name;
        $taxonomy_label_singular_name = get_taxonomy( $taxonomy )->labels->singular_name;

        // Loop through each WP_Term object for this taxomnomy and this post ID
        foreach ( $terms as $term ) {
            $term_id     = $term->term_id; // The term ID
            $term_slug   = $term->slug;  // The term slug
            $term_name   = $term->name;  // The term name
            $term_parent = $term->parent; // The term parent ID
            $description = $term->description; // The term description
            $term_link   = get_term_link( $term, $taxonomy ); // The term link

            // Set the term name in an array (for testing display)
            $term_names[] = $term_name;
        }
        // Output taxonomy label name with the coma separated terms
        echo '<p><strong>' . $taxonomy_label_name . ':</strong> ' . implode(', ', $term_names) . '</p>';
    }
}

Tested and works.