Skip to content

Instantly share code, notes, and snippets.

@BruceMcKinnon
Created August 13, 2019 03:46
Show Gist options
  • Save BruceMcKinnon/687074640621e32f50391decf6695259 to your computer and use it in GitHub Desktop.
Save BruceMcKinnon/687074640621e32f50391decf6695259 to your computer and use it in GitHub Desktop.
Display media images by category in a grid
add_shortcode('get-image-grid','get_images_by_category');
function get_images_by_category( $atts ) {
$retHtml = '';
$attribs = shortcode_atts( array(
'cat_slug' => "",
'link_to_file' => true,
'mime_type' => "image",
'class' => "cell small-6 medium-3",
), $atts );
$cat = get_category_by_slug( $attribs['cat_slug']);
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' => $attribs['mime_type'],
'post_status' => 'inherit',
'posts_per_page' => -1,
'cat' => $cat->term_id,
);
$query_images = new WP_Query( $query_images_args );
foreach ( $query_images->posts as $image) {
$retHtml .= '<div class="'.$attribs['class'].'">';
if ($attribs['link_to_file']) {
$retHtml .= '<a href="'.$image->guid.'" target="_blank">';
}
$thumb_ary = wp_get_attachment_image_src( $image->ID, 'full' );
$thumb_url = $thumb_ary[0];
$retHtml .= '<img src="' . $thumb_url .'" width="100%" height="auto" />';
$retHtml .= '<h4>'.$image->post_title.'</h4>';
if ($attribs['link_to_file']) {
$retHtml .= '</a>';
}
$retHtml .= '</div>';
}
return $retHtml;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment