Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 0 down vote accepted
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

share|improve this answer
    
Thanks, pretty simple. –  Francesco Oct 19 '12 at 10:07
    
I noticed that, using the code suggested by Mridul Aggarwal, the HTML is printed twice. I solved with this: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'; $output_string = ob_get_contents(); ob_end_clean(); return $output_string; } add_shortcode( 'ngvideo', 'wpse450_show_video' ); –  Francesco Oct 19 '12 at 12:10
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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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