This isn’t an issue with Attachments, have a look at http://php.net/substr
Thread Starter
KS
(@karl19)
Thanks a lot for the reply Jonathan! Sorry, didn’t mean to say that it was an issue with Attachments.
That said, I’m not sure substr will help me – the way I understand it, it would work on ALL of the images I output? Essentially, I’m outputting some 20 photos, each line look like above (with a comma at the end) and I need to remove the comma ONLY from the last line (ie the last photo in the loop).
I can do that with a normal while/if WP loop, but I don’t understand how I can achieve that with the below, as I don’t quite understand the syntax..
if( $attachments->exist() ) :
while( $attachment = $attachments->get() ) :
It looks like you are echoing out a comma right after the final curly brace (before the “\n” part)
// Change this:
echo "{image : '" . $attachments->src( 'full' ) . "'}," . "\n";
// To this:
echo "{image : '" . $attachments->src( 'full' ) . "'}" . "\n";
Thread Starter
KS
(@karl19)
Hi JR, thanks for your input!
You’re right, I’m echoing a comma at the end of the line, but this is needed – apart from the very last line. So if the loop spits out three images, the list should look like this:
{image : 'website/image.jpg'},
{image : 'website/image.jpg'},
{image : 'website/image.jpg'}
Essentially, I need an if/else, where it checks if it’s the last item in the attachments loop: if so, echo without comma, otherwise echo with comma.
Somehow I don’t seem to understand the attachments query loop, so I don’t know how to write the if/else into the loop from the first post above.
Ah, ok I see now. You’ll want to do something like this then:
$attachments = new Attachments( 'my_attachments', 1301 );
if( $attachments->exist() ) :
for ( $i=0; $i < $attachments->total(); $i++ ) :
$attachment = $attachments->get_single( $i );
if( $i == $attachments->total() - 1 ) :
echo "{image : '" . $attachments->src( 'full' ) . "'}" . "\n";
else :
echo "{image : '" . $attachments->src( 'full' ) . "'}," . "\n";
endif;
endfor;
endif;
This code is untested but should be pretty spot on or at least get you in the right direction. 🙂
Thread Starter
KS
(@karl19)
Excellent, thanks a lot JR! At first I got the right number of images, but it just output something from wp-includes. But when I changed:
$attachment = $attachments->get_single( $i );
to:
$attachment = $attachments->get( $i );
things started to work properly. Thanks again for your input, very much appreciated!