Extracting Post ID and passing through as an attribute in a shortcode

I have a custom post type made. I’m using ACF’s repeater to create a gallery on each post. I need to output them each in a shortcode using the post’s ID and passing it through as an attribute so it can look like [mbgc_gallery id="401"].

Here’s my function:

*--------------------------------------------------------------
## Gallery CPT
--------------------------------------------------------------*/
function mbgc_gallery_shortcode( $atts ) {

    extract( shortcode_atts(
        array(
            'id' => '',
        ), $atts )
    );
    $args = array(
        'post_type'     => 'galleries',
        'post_status'       => 'publish'
    );

    $post = get_post( $id );

    if ( $post ) :

        if( have_rows('mbgc_gallery') ):

            $html_out = '<div class="mbgc-gallery owl-carousel owl-theme">';

            while( have_rows('mbgc_gallery') ): the_row(); 

                // vars
                $image = get_sub_field('mbgc_image');
                $caption = get_sub_field('mbgc_caption');
                $title = get_sub_field('mbgc_title');
                $sub_title = get_sub_field('mbgc_sub_title');

                if ( $image ) :         
                    $html_out .= '<div class="mbgc-gallery-item">';

                        if ( $caption ) : 
                            $html_out .= '<div class="mbgc-slide-caption">';
                                $html_out .= '<h4>' . $caption . '</h4>';
                                $html_out .= '<div class="mbgc-slide-titles">';
                                    $html_out .= '<h6>' . $title . '</h6>';
                                    $html_out .= '<h6>' . $sub_title . '</h6>';
                                $html_out .= '</div>';
                            $html_out .= '</div>';
                        endif;

                        $html_out .= '<div class="mbgc-slide"><img src="' . $image['url'] . '" alt="' . $image['alt'] . '" /></div>';
                    $html_out .= '</div>';
                endif;

            endwhile;

            $html_out .= '</div>';

        endif;

    endif;

    return $html_out;

}
add_shortcode('mbgc_gallery', 'mbgc_gallery_shortcode');

So the two things I’m not sure about, do I need the $args I have? Also what’s the correct way to pull the ID is $post = get_post( $id ); the wrong thing to call?

Read more here: Extracting Post ID and passing through as an attribute in a shortcode

Leave a Reply

Your email address will not be published. Required fields are marked *