List WordPress Post and Related Attachments outside of a post page

I’ve been having difficulties with some new functionality I’ve been trying to create. Basically I have a custom page setup that displays a list of all posts with a specific tag. What it needs to do is also display each attachment associated with that post, beside the post name. I can get this working on the actual post page, but since this is a custom page it doesn’t want to display the attachment url.

Here is what I have so far:

$args = array 
    (
        'post_type' => 'attachment',
        'post_mime_type' => 'audio',
        'numberposts' => -1,
    );

    query_posts('portfolio-tags=apple&post_type=portfolio&posts_per_page=-1&orderby=title&order=asc'); // query to show all posts independant from what is in the center;
    if (have_posts()) :
        echo '<ul>';
        while (have_posts()) : the_post(); ?>
            <li>
                <span><?php echo the_title();?></span>
                <span><a href="<?php echo get_attachment_url($attachment->ID);?>" target="_blank">Demo</a></td>
            </li>
        <?php  endwhile;
        echo '</ul>';
    endif;
    wp_reset_query();

Any help would be greatly appreciated. I’ve been stuck on this for a while now and hope I’m just overlooking a very simple solution.

Answer

First of all don’t use query_posts function, use the WP_Query class instead.

Secondary you forget to fetch attachments for a post. You can get attachments list by calling get_children function.

$args = array (
    'post_type' => 'attachment',
    'post_mime_type' => 'audio',
    'numberposts' => -1,
);

$the_query = new WP_Query( 'portfolio-tags=apple&post_type=portfolio&posts_per_page=-1&orderby=title&order=asc' );
if ( $the_query->have_posts() ) :
    echo '<ul>';
    while ( $the_query->have_posts() ) : 
        $the_query->the_post();
        $images =& get_children( 'post_type=attachment&post_mime_type=image' ); ?>
        <li>
            <span><?php echo the_title();?></span>
            <?php foreach ( $images as $attachment_id => $attachment ) : ?>
                <span><a href="<?php echo get_attachment_url( $attachment_id );?>" target="_blank">Demo</a></td>
            <?php endforeach; ?>
        </li>
    <?php  endwhile;
    echo '</ul>';
endif;
wp_reset_postdata();

Attribution
Source : Link , Question Author : William , Answer Author : Eugene Manuilov

Leave a Comment