php – Incorporating a link to a sprintf image-ThrowExceptions

Exception or error:

I am using the following code to output an image tied to a WordPress post:

    if ( $cover ) :
        return sprintf(
                '<img src="%1$s">',
                $cover
            );
    endif;

This does output the required image but I need it to be clickable to display the image in full using:

<a href="<?php echo esc_url( $cover( 'medium_large' ) ) ?>">

Please can somebody advise how I can bring the two together?

Thanks.

How to solve:

So, I don’t know what your code does, or how are the variables defined, but this will generate the output you want:

function cover($cover = '') {
    if ( '' !== $cover ) :
        return sprintf(
            '<a href="%1$s"><img src="%1$s"></a>',
            $cover
        );
    endif;
}

echo cover('/path/to/my/image.png');

The above will output the following code:

<a href="/path/to/my/image.png">
    <img src="/path/to/my/image.png">
</a>

Keep in mind, that I do suppose you already know how to get the post cover image URL, and that’s why I have make the function to accept the cover image URL only.


Update #1

If you want to display different sizes images when you click the link you could do the following:

function cover($cover_link = '', $cover_img = '') {
    if ( '' !== $cover ) :
        return sprintf(
            '<a href="%1$s"><img src="%2$s"></a>',
            $cover_link,
            $cover_img
        );
    endif;
}

And then use the function cover inside the WordPress loop as following:

if ( have_posts() ) {
    while( have_posts() ) {
        the_post();

        // ... HTML or PHP Code you need for your loop

        $cover_link = get_the_post_thumbnail_url(get_the_ID(), 'full');
        $cover_img = get_the_post_thumbnail_url(get_the_ID(), 'post-thumbnail');

        if ( $cover_link && $cover_img ) {
            echo cover($cover_link, $cover_img);
        }

        // ... HTML or PHP Code you need for your loop
    }

}

Update #2

In the above example, I’ve used the image sizes full and post-thumbnail. In case you need to have custom sizes for your uploaded images you could use in the functions.php code like the following:

add_image_size( 'my_big_image_size', 1000, 1000, true);
add_image_size( 'my_small_image_size', 500, 500, true);

And then, inside the loop, you could change the following code:

$cover_link = get_the_post_thumbnail_url(get_the_ID(), 'full');
$cover_img = get_the_post_thumbnail_url(get_the_ID(), 'post-thumbnail');

To this:

$cover_link = get_the_post_thumbnail_url(get_the_ID(), 'my_big_image_size');
$cover_img = get_the_post_thumbnail_url(get_the_ID(), 'my_small_image_size');

Leave a Reply

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