Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

php - Show images that are in posts from a particular category to be displayed in a grid gallery

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:

  1. why the code is not getting other images from the other posts and

  2. how can i display them in a grid gallery view instead of a long list

I would really appreciate any help. thanks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...