0

I managed to get all the images of a gallery from another page using get_post_gallery() and I entered a description for each of them in the edit gallery window.

I tried using get_image_tag() to get the attributes from all images including the title. The thing is that it shows all the attributes while I only want the title attribute.

Also, it always show "1" in each title attribute.

My php code:

$gallery = get_post_gallery(7, false );
$imageIds = explode(',', $gallery['ids']);

// THE VALUES ARE HIGH TO AVOID THE EMPTY OUTPUT THAT OCCUR FOR SOME REASON
$randIds = array_rand($imageIds, 20);
for($i = 15; $i < 20; $i++)
{
    $image = wp_get_attachment_image_src($randIds[$i], 'large');
    $line = '<li><img src="';
    $line .= $image[0];
    $line .= '" title="';
    //$line .= 
    $line .= '"/></li>';
    echo $line;
    echo "GET_IMAGE_TAG";
    echo get_image_tag($randIds[$i], false, true, false);
}

And here is the HTML output I have for each for one iteration:

<li><img src="http://mywebsite.com/wp-content/uploads/2014/12/PA107885-768x1024.jpg" title=""/></li>
GET_IMAGE_TAG
<img src="http://mywebsite.com/wp-content/uploads/2014/12/PA107885-225x300.jpg" alt="" title="1" width="225" height="300" class="align size-medium wp-image-32" />

How can I only get the title attribute without having to scrap all my code?

2

WordPress actually uses a Built-in Post Type for Attachments ( called attachment ) so you can use some of the same functions like get_the_title() which is what you're looking for. Though, I did take some liberties by modifying your code below, using a foreach instead of a for loop:

$gallery = get_post_gallery( 7, false );    // Attempt to get Post Gallery

if( ! empty( $gallery ) ) {                 // IF Gallery Exists, proceed
    $imageIds = explode( ',', $gallery['ids'] );    // Get an array of Gallery IDs
    $randIds  = array_rand( $imageIds, 20 );        // Randomize array

    foreach( $randIds as $imageId ) {               // Foreach instead of For, just easier
        $image = wp_get_attachment_image_src( $imageId, 'large' );
        echo '<li><img src="' . $image[0] . '" title="' . get_the_title( $imageId ) . '" /></li>';
    }
}
  • Thanks! I didn't know that get_the_title() worked too with images. I used a for loop instead of a foreach because for some reason I get blank images at the beginning of the array, so I just skip them in the code. – TheBird956 Feb 10 '15 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.