0

I am developing a shortcode for wordpress. My shortcode and widget both need to connect to an external database in order to pull in formation.

My first question is what hook do i use to connect to an external db. The way I have it set up currently it tells me the header has already been sent. I need it to send with the header to make the clean connect. I do not want to use output buffer if i don't have to. I want to make a clean connect. What hook do i use to make a connect and not get the header error?

My second question is: Is there a way for this hook to only be called on certain pages? I don't want to make this connect on every page just on the pages that contain the short code. Is there an if statement or some sort of hook filter so that the db connect is only made when needed instead of being called on every page load. Thanks.

user982853
  • 2,470
  • 14
  • 55
  • 82

1 Answers1

0

The "wp" hook is run after the current $post is set but before the headers are output.

So you should be able to do a check like if(strpos($post->post_content, "[shortcode]") !== false) to determine if the DB connect code should run.

You would use that hook like:

add_action("wp", "my_wp"); //where "my_wp" is the name of your function
strangerstudios
  • 367
  • 3
  • 10
  • Be sure to check for extra whitespace above, below, or inside your plugin code if you are getting random errors and notices about headers already being sent. – strangerstudios Apr 09 '12 at 15:47
  • Thanks for the reply but i am still getting the header sent error. I checked all my white space and there is none. Any other suggestions? Thanks. – user982853 Apr 09 '12 at 16:02
  • After some testing i see that on the front end it works (no error) but when im logged in to the back end admin area im getting the error. – user982853 Apr 09 '12 at 16:16
  • Not sure what i did but it seems to be making the connect with no errors now. But i do have one other problem now. The short code doesn't render in the post, tells me no record set as if the connect is being closed. If i put the variable echos with the wp hook it will render them in the head before html but for some reason if i call them in the shortcode it does not render. Ill post another question. Thanks. – user982853 Apr 09 '12 at 16:39