Function as Shortcode

/*
Function as Shortcode Technique

Run functions in "Shortcode Mode" - If functions used for shortcode are output to the browser they will display above whatever content you place in your pages or posts. Not good. This method eliminates the need to write "mirrored" funcitons of your main ones just for shortcode.
*/

//Main plugin function
function main_function($shortcode = false){
if($shortcode) ob_start(); //If shortcode halt browser output

$testvar = 'This is an output test on: ' . $_SERVER['HTTP_HOST'];

?>
<div class="test">
<p><?php echo $testvar; ?></p>
</div>
<?php

//If shortcode store output in variable and return
if($shortcode){
$main_function_output = ob_get_contents();
ob_end_clean();
return $main_function_output;
}
}

//Run Shortcode - [my_shortcode]
function run_my_shortcode($atts){
extract(shortcode_atts(array(
'arg1' => 'Not Set',
'arg2' => 'Not Set'
), $atts));

return main_function(true);
}

add_shortcode('my_shortcode','run_my_shortcode');
?>

0 Comments

You must be logged in to post a comment.