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
Pull the
add_action()
outside of the function, and put the conditional inside the callback. Also, if you’re printing a script directly, usewp_print_scripts
instead ofwp_head
. You also have a syntax error.Try turning your code around:
As well, check in your theme’s files (most likely
header.php
) to make sure that thewp_head()
function is being called, and make sure that theMyOptionName
option is set for the site.Edited to add — You should also use
wp_enqueue_script()
to add Javascript to your site, rather than just dumping them into the<head>
.References
wp_head
(action)wp_head()
(function)get_option()
wp_enqueue_script()
see below code.Add
IF
statement inside the function.The “wp_head” action hook is triggered within the “head” section.
wp_enqueue_script() is used for executing scripts and wp_enqueue_style is for stylesheet from Plugin.
“WP_PLUGIN_URL.” will get data from plugin folder of themes.
“Test plugin” is your plugin Name
“pluginstyle.css” plugin stylesheet.
“jquery-min.js” plugin script.