Image-Output mit srcset anhand der Bild-ID erhalten
Das Snippet generiert anhand der Bild-ID und gewünschter Größe das Markup für ein Bild mit (falls verfügbar) srcset und sizes, mit width, height, alt-Text und Caption, falls eine Bildbeschriftung vorliegt.
$src = wp_get_attachment_image_src( $image_id, $image_size );
$alttext = get_post_meta( $image_id, '_wp_attachment_image_alt', true) ? get_post_meta( $image_id, '_wp_attachment_image_alt', true : get_post_field('post_excerpt', $image_id);
$caption = get_post_field('post_excerpt', $image_id);
$props = array();
$allow = array(
'a' => array(
'href' => array(),
'title' => array()
),
'br' => array(),
'em' => array(),
'strong' => array()
);
$props['src'] = $src[0];
$props['width'] = $src[1];
$props['height'] = $src[2];
$props['alt'] = $alttext;
/* abwärtskompatibel */
if ( function_exists( 'wp_get_attachment_image_srcset' ) ) $props['srcset'] = wp_get_attachment_image_srcset( $image_id, $image_size );
if ( function_exists( 'wp_get_attachment_image_sizes' ) ) $props['sizes'] = wp_get_attachment_image_sizes( $image_id, $image_size );
$output .= '<figure class="my-figure-class">';
$output .= '<img class="my-image-class wp-image-'.absint($image_id).'" ';
foreach( $props as $prop => $val) {
$output .= esc_attr($prop) . '="' . esc_attr($val) . '" ';
}
$output .= '/>';
if ( $caption ) {
$output .= sprintf( '<figcaption class="my-image-caption-class">%s</figcaption>', wp_kses( $caption, $allow ) );
}
$output .= '</figure>';
echo $output;
Code-Sprache: PHP (php)
Kommentarformular bitte nicht für Supportanfragen verwenden