Skip to content

Instantly share code, notes, and snippets.

@ashhitch
Created May 3, 2017 15:06
Show Gist options
  • Select an option

  • Save ashhitch/7f6ac642b116f56e3d7aa19f0df5d1b6 to your computer and use it in GitHub Desktop.

Select an option

Save ashhitch/7f6ac642b116f56e3d7aa19f0df5d1b6 to your computer and use it in GitHub Desktop.
Generate Picture element in WordPress
<?php
// function to get image Alt tag
function get_img_alt( $image ) {
$img_alt = trim( strip_tags( get_post_meta( $image, '_wp_attachment_image_alt', true ) ) );
return $img_alt;
}
// fucntion to get src of each image
function get_picture_srcs( $image, $mappings ) {
$arr = array();
foreach ( $mappings as $size => $type ) {
$image_src = wp_get_attachment_image_src( $image, $type );
$arr[] = '<source srcset="'. $image_src[0] . '" media="(min-width: '. $size .'px)">';
}
return implode( array_reverse ( $arr ) );
}
// Main function to generate <picture> element
function get_picture($image, $sizes = null, $class="img-fluid", $placeholder = false) {
if ($image == null):
if ($placeholder) {
$picElm = '<picture>
<img src="' . get_template_directory_uri().'/images/awaiting.png' . '" class="'.$class.' awaiting-photo" alt="">
</picture>';
}
else {
$picElm = null;
}
else:
if ($sizes) {
if(is_string($sizes)) {
$mappings = array('0' => $sizes);
} else {
$mappings = $sizes;
}
}
else {
// Set Your default Sizes
$mappings = array(
'0' => 'thumb-sm',
'768' => 'thumb-md',
'1200' => 'thumb-lg'
);
}
$img = wp_get_attachment_image_src( $image, $mappings[0]);
$picElm = '<picture>
'.get_picture_srcs($image, $mappings ).'
<img src="' . $img[0] . '" class="'.$class.'" alt="' . get_img_alt( $image ) . '">
</picture>';
endif;
return $picElm;
}
/*
Example Usage:
//Single size as string
get_picture($image['ID'], 'thumbnail');
//Example with image size profiles
$mappings = array(
'0' => 'gallery-sm',
'768' => 'gallery-md',
'1200' => 'gallery-lg'
);
echo get_picture($image['ID'], $mappings);
// Return Place holderm if no image
get_picture($image['ID'], 'thumbnail', true);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment