I am trying to add some code to the head (namely a block of tracking script) via a plugin I am making.
The plugin has an interface where the user enters some details which are then added to the options table. This is all working perfectly fine so far. But then I want to write a conditional statement if there is an open then add to head. Basically I have this all in the main plugin file and it looks like this;
if(get_option( 'MyOptionName' )){
function testingone(){ ?>
<script>var Script = GoesHere; </script>
<?php ;}
add_action('wp_head','testingone');
}
I have tried placing this inside the actual block that pulls the data and then adds to options, but that didn’t work, then I decided to do it this way, where it looks to see if there is an option in the table but this also doesnt inject anything to the head. Some places I have seen people put the add_action above the function, but in the codex it shows an example of it below. but either way I have tried and failed.
Can anyone see where this is going wrong?
Cheers
4 Answers
Pull the add_action()
outside of the function, and put the conditional inside the callback. Also, if you’re printing a script directly, use wp_print_scripts
instead of wp_head
. You also have a syntax error.
function testingone(){
if( get_option( 'MyOptionName' ) ) {
?>
<script>var Script = GoesHere; </script>
<?php
}
}
add_action( 'wp_print_scripts','testingone' );