Skip to content

Instantly share code, notes, and snippets.

@terrymun
Created December 17, 2014 00:33
Show Gist options
  • Save terrymun/3a73f8a282d9d2870258 to your computer and use it in GitHub Desktop.
Save terrymun/3a73f8a282d9d2870258 to your computer and use it in GitHub Desktop.
Responsive Photoset — WordPress function
// Declare "custom_photoset" function
function custom_photoset($attr) {
$args = shortcode_atts(
array(
'ids' => '',
'layout' => ''
),
$attr,
'photoset'
);
// Create arrays from ID and layout
$id_arr = explode(',', $args['ids']);
$layout_arr = explode(',', $args['layout']);
$output; $grid_class; $count=0;
// Each comma-separated layout value is a row
foreach($layout_arr as $key => $layout_item) {
// Create row
$photoset_row = '';
// Create individual image elements
for ($i=0; $i < intval($layout_item); $i++) {
// Create smart classes for images
$photoset_class = 'coord-'.strval($key+1).'-'.strval($i+1).' row-'.strval($key+1).' item-'.strval($i+1).' '.$pos;
// Get smaller image for photoset
$img_attr = wp_get_attachment_image_src($id_arr[$count], $size='medium');
// Get larger image for link
$img_url = wp_get_attachment_image_src($id_arr[$count], $size='large');
// Access image metadata
$img = get_post($id_arr[$count]);
$img_meta['alt'] = get_post_meta($img->ID, '_wp_attachment_image_alt', true);
$img_meta['caption'] = $img->post_excerpt;
$img_meta['desc'] = $img->post_content;
$img_meta['title'] = $img->post_title;
// Append images to row
// We can rely on PHP to compute aspect ratio
// instead of jQuery
$photoset_row .= '<figure class="photoset-item '.$photoset_class.'"><a href="'.$img_url[0].'"><img src="'.$img_attr[0].'" alt="'.$img_meta['alt'].'" title="'.$img_meta['title'].'" data-img-width="'.$img_attr[1].'" data-img-height="'.$img_attr[2].'" data-img-aspect-ratio="'.($img_attr[1]/$img_attr[2]).'" /></a><figcaption>'.$img_meta['caption'].'</figcaption></figure>';
$count++;
}
// Close row
$output .= '<div class="photoset-row row-'.$key.' items-'.intval($layout_item).'" data-item-count="'.intval($layout_item).'">'.$photoset_row.'</div>';
}
// Wrap output with a final <div>
return '<div class="photoset">'.$output.'</div>';
}
// Add shortcode
add_shortcode('photoset', 'custom_photoset');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment