Custom Linked Images in WordPress Page Gallery

Let’s say you spent all weekend building your girlfriends portfolio site and you want an easy way to output linked images on a page. You might think “easy enough, I’ll just put in a gallery on the page. She can manage her images from there!” But then you hand your site to your gf and she says “can I link those images to other sites?”…

We’ll, yeah. Here’s how.

She will manage images on the page through the wordpress gallery. For every image she wants to link out some place, you will have her put the link in the “alt text” input field on the backend:

alt_textThen you will pick this alt text out of the post meta and read it into your template. Here’s an example:

    $gallery = get_post_gallery( get_the_ID(), false );
    $idsArr = explode(',', $gallery['ids']);
    $template = '';
    if($idsArr) {
        foreach($idsArr as $key => $id) {
            $url = wp_get_attachment_url( $id );
            $alt = '#';
            $alt = get_post_meta($id, _wp_attachment_image_alt, true);
            $template .=    '<a href="' . $alt . '"><img src="'.$url.'" /></a>';
            $template .=    '<br />';
    echo $template;

This code┬álives in “content-page.php” of my theme file, but you may have reason to put in into your “page.php” file directly.


Leave a Reply

Your email address will not be published. Required fields are marked *