How To Write A Javascript Function Inside The Functions.php Of Wordpress?
I'm altering a plugin on developer recommendations (See latest post), which advices to write a bit of Javascript in the functions.php of Wordpress. Now, when I did that my whole wo
Solution 1:
there is a better and standard way in wordpress
<?phpfunctionadd_js_functions(){
?><script>// your js functions here </script><?php
}
add_action('wp_head','add_js_functions');
Solution 2:
As you are using double quotes, PHP will think that the variable with $
signs as a php variable. You need to either change them to single quote and rearrange the code either you need to take a look at heredoc which is suitable for situations like this.
echo <<<'EOT'
<script>
( function() {
var categories = {};
var $group = jQuery();
jQuery('select.app_select_services option').remove().each(function() {
var $option = jQuery(this),
contents = $option.text().split(' - '),
group = jQuery.trim(contents[1]);
if (!categories.hasOwnProperty(group)) {
var optGroup = jQuery('<optgroup />', { label: group });
optGroup.appendTo('select.app_select_services');
categories[group] = optGroup;
}
categories[group].append(jQuery('<option />', {
text: jQuery.trim(contents[0]),
value: jQuery(this).val()
}));
});
} )();
</script>
EOT;
Solution 3:
You need to wait for DOM to be fully initialized. So wrap your jQuery snippet within ready
handler. Or even better place is to place this snippet in your footer.php
file before closing </body>
tag.
jQuery(document).ready(function($) { // <-- wrap itvar categories = {};
var $group = jQuery();
jQuery('select.app_select_services option').remove().each(function() {
var $option = jQuery(this),
contents = $option.text().split(' - '),
group = jQuery.trim(contents[1]);
if (!categories.hasOwnProperty(group)) {
var optGroup = jQuery('<optgroup />', { label: group });
optGroup.appendTo('select.app_select_services');
categories[group] = optGroup;
}
categories[group].append(jQuery('<option />', {
text: jQuery.trim(contents[0]),
value: jQuery(this).val()
}));
});
});
Solution 4:
When you use double quotes ""
to define JS string, PHP will interpret $group
as a variable. In order to fix it, you need to use single quotes ''
instead.
Post a Comment for "How To Write A Javascript Function Inside The Functions.php Of Wordpress?"