How to format shortcode’s HTML in external file

I need to add a shortcode in my theme and I would like to put the HTML code not in the function which creates the shortcode but in a template file in my theme directory.

Now I have

function wpse450_show_video( $atts ) {
    extract(shortcode_atts(array(
        'id'        => 0
    ), $atts ));

    if( is_numeric($id) ) {
        $ngvideo_title = get_the_title($id);
    }
    return '<div>'.$ngvideo_title.'</div>';
}
add_shortcode( 'ngvideo', 'wpse450_show_video' );

I would like to put the <div>'.$ngvideo_title.'</div> stuff in an external file.

How to do this?

1 Answer
1

function wpse450_show_video( $atts ) {
    extract(shortcode_atts(array(
        'id'        => 0
    ), $atts ));

    if( is_numeric($id) ) {
        $ngvideo_title = get_the_title($id);
    }

    ob_start();
    include 'path/to/file/video.php';

    return ob_get_clean();
}

add_shortcode( 'ngvideo', 'wpse450_show_video' );

You can use $id, $atts in our file as you would in your function. The code in your file will behave just like it would have in your function with just one difference that you’ll have to echo the stuff instead of returning it like you would for your function

Leave a Comment