Search code examples
wordpresscustom-post-typetaxonomy

Get attachments based on a custom post types post ID


I don't know if this is possible but I'll try to explain.

I have a custom post type (creatives) and a taxonomy (image-sort). Every post in the CPT is a person (a creative). They can upload images and sort them by choosing which categories (the 'image-sort' taxonomy) they belong to.

There are multiple creatives, and they will post images to different categories. Some to all of them, some to just a few.

Every creative have their own page with a dynamic listing of which categories they have posted content to. My problem is though that if one creative have posted to 'cat-1' and 'cat-2' everybody get that listed out on their respective page. What I want is to only show 'cat-1' and 'cat-2' on the creative which has posted to those categories. If another creative has posted to 'cat-1' and 'cat-3' I only want those two to appear on his page.

Does this make sense?

<ul>
<?php
    $terms = get_terms('image-sort');
    if ( $terms && !is_wp_error($terms) ) :
    foreach ( $terms as $term ) :
?>
<li><a href="?term=<?php esc_attr_e($term->slug); ?>"><?php esc_html_e($term->name); ?</a></li>
<?php endforeach; endif; ?>
</ul>

Solution

  • Not sure if i understand you, but if i do, try replacing this line:

    $terms = get_terms('image-sort');
    

    with the following line:

    $terms = wp_get_object_terms(get_the_ID(), 'image-sort');
    

    EDIT

    Try fetching the terms with the following piece of code:

    <?php
    
    // get all attachments of the current post
    $attachments = get_children('post_parent=' . get_the_ID() . '&post_type=attachment&post_status=any&posts_per_page=-1');
    
    // we're saving the terms here
    $all_terms = array();
    
    // looping through all attachments
    foreach( $attachments as $attachment) {
        $terms = wp_get_object_terms($attachment->ID, 'image-sort');
        if ($terms) {
            // looping through all attachment terms and adding them to the main array
            foreach ( $terms as $term ) {
                $all_terms[$term->term_id] = $term;
            }
        }
    }
    
    ?>