Cray
Cray

Reputation: 5493

Display WordPress page content with shortcode and show embedded shortcode

I'm using a Custom Post Type to display banners on my site. The content could be text, images and also shortcodes (e.g. a button shortcode).

If I display the content with my shortcode, everything looks finde. Except of shortcodes inside the banner itself.

Is there any way to render that shortcode?

Here's my shordcode:

// [banner id="" class=""]
function shortcode_banner( $atts, $content ){
    extract(shortcode_atts(array(
        'id'    => '',
        'class' => '',
    ), $atts));

    $banner_id  = $id;
    $content    = get_post_field('post_content', $banner_id);

        return '<div class="'.$class.'">'.wpautop($content).'</div>';

}
add_shortcode( 'banner', 'shortcode_banner' );

Upvotes: 0

Views: 1936

Answers (1)

Nikos M.
Nikos M.

Reputation: 8345

Try below code:

// [banner id="" class=""]
function shortcode_banner( $atts, $content ) {
    extract(shortcode_atts( array(
        'id'    => '',
        'class' => '',
    ), $atts ) );

    $banner_id = $id;
    $content   = get_post_field( 'post_content', $banner_id );

    return '<div class="'.$class.'">'.wpautop( do_shortcode( $content ) ).'</div>';
}

or if you expect to have recursive shortcodes:

function recursively_do_shortcode( $content ) {
    $content2 = $content;
    do{
       $content = $content2;
       $content2 = do_shortcode( $content );
    } while( $content2 !== $content ); // presumably you can test if shortcodes exist in content as well
    return $content2;
}

// [banner id="" class=""]
function shortcode_banner( $atts, $content ){
    extract( shortcode_atts( array(
        'id'    => '',
        'class' => '',
    ), $atts ) );

    $banner_id = $id;
    $content   = get_post_field( 'post_content', $banner_id );

    return '<div class="'.$class.'">'.wpautop( recursively_do_shortcode( $content ) ).'</div>';
}

Reference: do_shortcode

Upvotes: 1

Related Questions