How to include a file in shortcode function in wordpress

Nov 15th 22 byAdmin inWordPress

hoew to


// Shortcode implementation
function magic_stuff($atts) {

   // turn on output buffering to capture script output
	
   ob_start();

   // include file (contents will get saved in output buffer)
	
   include(TEMPLATEPATH.'/wp-content/prugins/magic-plugin/magic-code.php');

   // save and return the content that has been output

   $content = ob_get_clean();
   return $content;
}
//register the Shortcode handler
add_shortcode('magic', 'magic_stuff');

Leave a comment

3 comments

MH
Mahmud Hossain
July 16, 2026

Well written. Bookmarked this for my team's reference. Looking forward to more content like this.

SB
Sumaiya Begum
July 15, 2026

Does this approach also work for larger datasets? Our team is dealing with something similar at scale.

RK
Rafiq Khan
July 14, 2026

Really insightful article! This is one of the clearest explanations I've come across. The examples make it very easy to understand.

AD
AdminAdminJuly 14, 2026

Thank you Rafiq! Glad it was helpful.