2

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?

2
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

  • 1
    Small mistake. I updated the code above. The change is ob_get_flush() becomes ob_get_clean(). You don't need a variable then – Mridul Aggarwal Oct 19 '12 at 12:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.