M. Hussain
M. Hussain

Reputation: 1

How to fetch images from a CPT and show it on a page with PHP

I added some custom taxonomies named "categories" to create categories for my quiz and I have to show the list of all the quizzes. I am trying to create a shortcode for those categories but I am not able to fetch the image of the quiz (which one can upload in quiz description). I can fetch the quiz title and its permalink to start the quiz but not the image. If anyone knows how to do it, please help me.

Here is my code:

function fca_qc_quiz_shortcode($atts){

    $atts = shortcode_atts( array(
        'category' => ''
    ), $atts );
    
    $quiz_category = $atts['category'];
    
    $args = array(
        'post_type' => 'fca_qc_quiz',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'quiz_categories',
                'field' => 'slug',
                'terms' => $quiz_category
            )
        )
    );
    
    $quizes = new WP_Query($args);
    
    $html = '';
    
    if($quizes->have_posts()){
        
        while($quizes->have_posts()){
            
            $quizes->the_post();
            
            $quiz_title = get_the_title();
            $quiz_id = get_the_ID();
            

            $quiz_description = get_post_meta( $quiz_id, 'fca_qc_image', true );
            $quiz_image_id = get_post_meta( $quiz_id, 'fca_qc_quiz_description_img', true );
            $quiz_image = wp_get_attachment_image_src( $quiz_image_id, 'thumbnail' );
            
            $html .= '<div class="quiz">';
            $html .= '<h2>'.$quiz_title.'</h2>';
            
            if(!empty($quiz_image)){
                $html .= '<img src="'.$quiz_image[0].'" alt="'.$quiz_title.'">';
            }
            
            $html .= '<p class="quiz-desc">'.$quiz_description.'</p>';
            $html .= '<a href="'.get_permalink().'">'.__('Start Quiz', 'fca_qc').'</a>';
            $html .= '</div>';
            
        }
        
        wp_reset_postdata();
        
    }else{
        
        $html .= '<p>'.__('No quiz found in this category', 'fca_qc').'</p>';
        
    }
    
    return $html;

}

add_shortcode( 'quizzes_by_category', 'fca_qc_quiz_shortcode' );

It is currently showing like this:

HTML result

Upvotes: 0

Views: 53

Answers (0)

Related Questions