Support

Account

Home Forums Front-end Issues How can I get the caption of the used image in an picture element Reply To: How can I get the caption of the used image in an picture element

  • Yes, that’s exactly it.

    Why doesn’t it work? From what you’ve said, you have 3 images and they display according to the screen size – is that right?

    If so, you then want the right image caption to be shown, depending on the right image being displayed, based on the screen size – is that right?

    If so, then you can use media queries, for example:

    
    
    <style>
    @media screen and (min-width: 991.99px) {
    	.desktop-caption {
    		display: block;
    	}
    	.tablet-caption {
    		display: none;
    	}
    	.phone-caption {
    		display: none;
    	}		
    }	
    @media screen and (min-width: 575.99px) and (max-width: 991.98px)  {
    	.desktop-caption {
    		display: none;
    	}
    	.tablet-caption {
    		display: block;
    	}
    	.phone-caption {
    		display: none;
    	}	
    }
    @media screen and (max-width: 575.98px) {
    	.desktop-caption {
    		display: none;
    	}
    	.tablet-caption {
    		display: none;
    	}
    	.phone-caption {
    		display: block;
    	}		
    }
    </style>
    
    <?php $headerbild = get_field('headerbild');
    if( $headerbild ): ?>
    <div class="hero-picture">
    	<figure class="media">
    		<picture>
    			<source media="(max-width: 575.98px)" srcset="<?php echo esc_url( $headerbild['headerbild_smartphone']['url'] ); ?>" alt="<?php echo esc_attr( $headerbild['headerbild_smartphone']['alt'] ); ?>" type="image/webp">
    			<source media="(max-width: 991.98px)" srcset="<?php echo esc_url( $headerbild['headerbild_tablet']['url'] ); ?>" alt="<?php echo esc_attr( $headerbild['headerbild_tablet']['alt'] ); ?>" type="image/webp">
    			<img class="img-fluid" src="<?php echo esc_url( $headerbild['headerbild_desktop']['url'] ); ?>" alt="<?php echo esc_attr( $headerbild['headerbild_desktop']['alt'] ); ?>" />
    		</picture>
    		<p class="credits desktop-caption"><?php echo $headerbild['headerbild_desktop']['caption']; ?></p>
    		<p class="credits tablet-caption"><?php echo $headerbild['headerbild_tablet']['caption']; ?></p>
    		<p class="credits phone-caption"><?php echo $headerbild['headerbild_smartphone']['caption']; ?></p>
    	</figure>
    </div>
    <?php endif; ?>

    Perhaps I’ve misunderstood but I’ve simply gone by the details you’ve given.