Get custom taxonomies from multiple posts

I’ve been looking around for half a day now but no success so far.

I’ve created a custom post type (recipe) and two custom taxonomies that go with it (type and cook). What I want is to be able to list all “cooks” from a group of recipes.

Read More

I can do it for a single recipe but I’m stuck with multiple ones.

Does anyone have any idea on how to achieve this?

Related posts

1 comment

  1. For each post add each term to a PHP associative array:

    foreach ( $posts as $post ) {
    
        $term_objects = get_the_terms( $post->ID, $taxonomy_name );
    
        foreach ( $term_objects as $term_object ) {
    
            // Store term objects by term name.
            $terms_list[ $term_object->name ] = $term_object;
        }
    }
    

    Let’s say Bob was listed as the cook on the first two recipes. When the first post is processed a field named Bob is added to $terms_list. On the second post the Bob field is overwritten with the same information (a term object).

    The result after looping through all posts is a list key => values where the keys are unique. Bob, for example, is only listed once.

    Since you didn’t provide any code or tell us what you wanted the output should look like, I made this example up using the get_posts() function to get the array of posts and used an unordered list to display the cooks names as links.

    $cooks = wpse_125356_get_terms_for_posts( get_posts( array( 'post_type' => 'recipe' ) ), 'cook' );
    
    if ( $cooks ) {
        echo "<ul>n";
        foreach ( $cooks as $cook ) {
    
            $url = get_term_link( $cook );
            if ( is_wp_error( $url ) ) {
                echo "t<li>{$cook->name}</li>n";
            } else {
                echo "t<li><a href='{$url}'>{$cook->name}</a></li>n";
            }
        }
        echo "</ul>nn";
    }
    
    
    /**
     * Get all unique terms for an array of posts for a given taxonomy.
     *
     * @param array $posts An array of post objects.
     * @param string $taxonomy_name The name of the taxonomy to retrieve.
     * @return array An array term objects ordered by term name.
     */
    function wpse_125356_get_terms_for_posts( array $posts, $taxonomy_name ) {
    
        $terms_list = array();
        foreach ( $posts as $post ) {
    
            $term_objects = get_the_terms( $post->ID, $taxonomy_name );
    
            // $term_objects can also be boolean false or a WP_Error object.
            if ( is_array( $term_objects ) ) {
                foreach ( $term_objects as $term_object ) {
    
                    // Store term objects by term name.
                    $terms_list[ $term_object->name ] = $term_object;
                }
            }
        }
    
        // Sort term objects by term name.
        ksort( $terms_list );
    
        // Return a list of term objects, if any.
        return array_values( $terms_list );
    }
    

Comments are closed.