0
votes

I need to get the captions of all images that I upload in the gallery with redux.

This is the code in theme options with redux framework: https://docs.reduxframework.com/core/fields/gallery/

I tried to show the captions on a WordPress site with this code (only for testing):

<?php 
    $attachmentIds = explode(',', $redux_demo['opt-gallery']);
    foreach($attachmentIds as $attachmentId): 
        $metaAttachment = wp_get_attachment_metadata( $attachmentId );
        echo '<pre>';
        print_r( $metaAttachment );
        echo '</pre>';
?>

But, this code returns me [caption] => (empty)

    Array(
    [width] => 330
    [height] => 180
    [file] => 2015/10/330x1805.jpg
    [sizes] => Array
        (
            [thumbnail] => Array
                (
                    [file] => 330x1805-150x150.jpg
                    [width] => 150
                    [height] => 150
                    [mime-type] => image/jpeg
                )

            [medium] => Array
                (
                    [file] => 330x1805-300x164.jpg
                    [width] => 300
                    [height] => 164
                    [mime-type] => image/jpeg
                )

        )

    [image_meta] => Array
        (
            [aperture] => 0
            [credit] => 
            [camera] => 
            [caption] => 
            [created_timestamp] => 0
            [copyright] => 
            [focal_length] => 0
            [iso] => 0
            [shutter_speed] => 0
            [title] => 
            [orientation] => 0
        )

)

The caption field has a value, but it seems the redux does not save the information or my code is wrong?

1

1 Answers

0
votes

This is the solution I was looking for:

In functions.php file:

function wp_get_attachment( $attachment_id ) {
    $attachment = get_post( $attachment_id );
    return array(
        'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
        'caption' => $attachment->post_excerpt,
        'description' => $attachment->post_content,
        'href' => get_permalink( $attachment->ID ),
        'src' => $attachment->guid,
        'title' => $attachment->post_title
    );
}

In your template file:

<?php 
    global $redux_demo;
    $myGalleryIDs = explode(',', $redux_demo['opt-gallery']);
    foreach($myGalleryIDs as $myPhotoID):
        $photoArray = wp_get_attachment($myPhotoID);
    ?>
        <a href="<?php echo wp_get_attachment_url( $myPhotoID ); ?>" class="lightbox" title="<?php echo $photoArray[caption]; ?>">
            <img src="<?php echo wp_get_attachment_url( $myPhotoID ); ?>" class="img-rounded" alt="<?php echo $photoArray[title]; ?>">
    </a>
<?php endforeach; ?>

I hope it helps! :-)