I’m a fairly new WP developer. I am trying to get my portfolio.php
to display all images attached to my custom post type ‘portfolio’, and then display them in a masonry format. I’ve managed to get them to show without the $post->post_type
query, but not much success when trying to limit WP to retrieving images attached to my custom post type. Any help will be much appreciated, and thanks in advance!
<?php get_header(); ?>
<div id="portfolio-wrapper">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php if ( $post->post_type == 'portfolio' ) {
$attachments = get_posts( array (
'post_type' => 'attachment',
'numberposts' => -1,
'post_parent' => $post->ID
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$imgurl = wp_get_attachment_url ($attachment->ID);
echo '<div class="portfolio-item">';
echo '<a href="'.$imgurl.'" rel="lightbox[portfolio-home]"><img class="portfolio" src="'.$imgurl.'"></a>';
echo '</div>';
}
}
}
?>
</div>
<?php endwhile; endif; ?>
<?php get_footer(); ?>
As requested, my solution. Not very elegant, but it works:
$query = new WP_Query( array( 'post_type' => 'portfolio', 'posts_per_page' => -1 ) );
if( $query->have_posts() ){
while($query->have_posts()){
$query->the_post();
$image_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'posts_per_page' => -1, 'post_parent' => get_the_ID(), 'order' => 'DESC' ) );
while( $image_query->have_posts() ) {
$image_query->the_post();
$imgurl = wp_get_attachment_url( get_the_ID() );
echo '<div class="portfolio-item">';
echo '<a href="'.$imgurl.'" rel="lightbox[portfolio-home]"><img class="portfolio" src="'.$imgurl.'"></a>';
echo '</div>';
}
}
}
Your solution (edited incorrectly into the question) should be workable but you should be able to accomplish the same with fewer queries.
ID
s– note thefields
argument.ID
s as the parent post.That works out to two primary queries. To wit:
The way you are doing it would mean one query for the
portfolio
posts, plus another image query for eachportfolio
result. That could mean dozens, hundreds, or even more queries depending on the size of your database.