I would really appreciate some help here.
I am trying to display images that are in posts from a particular category to be displayed in a grid gallery.
say i have posts under the category of "flower". These posts have images inside them of different flowers. I want to extract the most recent posts images and display them on grid gallery.
This is the code I have which uses a shortcode to pass the category id to filter posts by category. the code gets images from 1 post but nothing else even though when debugging, i can see other posts are being called with there attachments too!
<?php
/**
* Usage: [catgallery cat="11"]
* Attribute: array of category IDs
*/
add_shortcode('catgallery', 'cat_gallery_shortcode');
function cat_gallery_shortcode($atts){
$return = ''; // DEBUG: enable for debugging
$arr = array();
$cat_in = explode( ',', $atts['cat'] );
$catposts = new WP_Query( array(
'posts_per_page' => 20
, 'category__in' => $cat_in
) );
foreach( $catposts->posts as $post){
// DEBUG: Enable the next line to print the post title
$return .= '<strong>' . $post->post_title . '</strong><br />';
$return .= '<strong>' . $post->ID . '</strong><br />';
$args = array(
'post_type' => 'attachment'
, 'numberposts' => 20
, 'post_status' => null
, 'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments)
{
foreach ( $attachments as $attachment )
{
// DEBUG: Enable the next line to debug the attachement object
$return .= 'Attachment:<br /><pre>' . print_r($attachment, true) . '</pre><br />';
$arr[] = $attachment->ID;
}
}
}
// DEBUG: Disable the next line if debugging
$return = do_shortcode( '[gallery include="' . implode( ',', $arr ) . '" link="none" size="medium"]' );
return $return;
}
?>
This code is in my child theme function.php file
I need a fix for please:
why the code is not getting other images from the other posts and
how can i display them in a grid gallery view instead of a long list
I would really appreciate any help. thanks
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…