0

I'm trying to add a shortcode in my Wordpress functions.php file. I want the short code contents to be sent to a PHP function from another part of the website. This is the code:

function short_api($atts){
include (__DIR__.'/api/short_look_up.php');
$api_info = get_api_info($atts);
return $api_info;
}
add_shortcode('apii', 'short_api');

(The get_api_info() is a function in short_look_up.php) Is this the proper way to do this? Right now I'm getting an error and I'm not sure if it is because my include path is messed up, or if Wordpress isn't going to let me do this.

I would also like to know if this is 'bad form' in Wordpress.

0

1 Answer 1

1

Well, yea you kinda can do that. But it's bad practice and it's strongly discouraged. Cause when you call parent function the nested function is being called automatically. So basically the nested function is being called twice. Better and safest way to do it like-

// Include the file or write the nested function outside of the parent function 
include (__DIR__.'/api/short_look_up.php');
function short_api($atts){
    $api_info = get_api_info($atts);
    return $api_info;
}
add_shortcode('apii', 'short_api');
3
  • So, you just moved the include from within the function to directly above it?
    – jonbon
    Oct 24, 2016 at 19:27
  • Actually I moved it outside of the function. Better above because PHP is an interpreted language. It starts interpreting the script from top and executes before each ";". So its better including the file above.
    – CodeMascot
    Oct 24, 2016 at 19:35
  • Yeah, sorry, by 'above' I meant 'outside' of the function.
    – jonbon
    Oct 24, 2016 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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