I've created a custom post type and used CMB2 to add a file upload option to it, one that allows upload of multiple files. I'm using the following code in my single.php file to output all of the files that have been uploaded.
$files = get_post_meta( get_the_ID(), $file_list_meta_key, 1 );
if( $files != '' ) {
echo '<div class="ad-photos">';
// Loop through them and output an image
foreach ( (array) $files as $attachment_id => $attachment_url ) {
echo '<a href="' . wp_get_attachment_url( $attachment_id) . '" data-fancybox="group" >' . wp_get_attachment_image( $attachment_id, $img_size ) . '</a>';
}
echo '</div>';
}
That code works well. Now I need a code that will output only the first file that's been uploaded. I've searched extensively for this, and come up with many different ways to accomplish this. From what I can gather, the best way is to use array_slice
. I've read everything I can about array_slice
and tried all sorts of things, but for the life of me I can't figure out how to implement it into the code I have there.
This was my best logical attempt:
$otherfiles = get_post_meta( get_the_ID(), $file_list_meta_key, 1 );
if( $otherfiles != '' ) {
// Loop through them and output an image
$otherfiles = array_slice( $otherfiles, 0,1);
foreach ( $otherfiles as $attachment_id => $attachment_url ) {
echo '<a href="' . wp_get_attachment_url( $attachment_id) . '" data-fancybox="group" >' . wp_get_attachment_image( $attachment_id, $img_size ) . '</a>';
}
}
And it seems to get me close, because it does cause it to loop only once, but it's not actually grabbing the file url. It just outputs an empty <a>
tag.
I feel like I'm just missing something simple here, but I've read everything I can find and tried everything I can think of and can't figure it out. The above code it the closest I've gotten out of many different methods.
Any help or nudge in the right direction is appreciated. And if there is a better way of accomplishing this, I'm all ears! I've also tried using a for
loop instead, as some people say that's a better option, but I haven't been able to figure out how to modify the code I have into a for
loop. So if anyone can show me how to do that I'd be very grateful. I copied the code I'm using from the CMB2 documentation, and I just don't understand it well enough to modify it properly I guess.