Is there a way to use wp_enqueue_script for adding JavaScript directly? - wordpress

Is there a way of adding Javascript to a page directly but having Wordpress to wait for jQuery to load? Just as with using wp_enqueue_script?
In the custom page template I have the following code:
<?php if (isset($_GET['status']) && $_GET['status'] == 'newly_created') : ?>
<script>
$(function() {
App.dialogs.afterPetitionCreate();
});
</script>
<?php endif; ?>
Wordpress barks that $ is undefined. Now I do not want to load a entire .js file just to call that function. So in that sense wp_enqueue_script isn't an option. I only want to fire some JavaScript directly on the page but I do want to wait for jQuery to load.
This is what I also tried, adding the JavaScript to the footer with Wordpress:
<?php if (isset($_GET['status']) && $_GET['status'] == 'newly_created') :
add_action('wp_footer', 'my_footer_scripts');
function my_footer_scripts() { ?>
<script>
$(function () {
App.dialogs.afterPetitionCreate();
});
</script>
<?php } ?>
<?php endif; ?>
But unfortunately the same error appears $ is undefined.
So what would be the correct way to quickly load some Javascript on a custom Wordpress page template AND wait for jQuery to load?

I do not think this is a good practice.
It is better to change logic to something like this:
<?php if (isset($_GET['status']) && $_GET['status'] == 'newly_created') : ?>
<input type='hidden' id='status' name='status' value='newly_created'>
<?php endif; ?>
script.js:
$(function() {
if ( $('#status').val() === 'newly_created' ) {
App.dialogs.afterPetitionCreate()
}
});
and
wp_enqueue_script( 'afterPetitionCreate', '/path/to/script.js', array( 'jquery' ), '', true );
p.s. you can wrap wp_enqueue_script() into is_page_template( 'my-cool-page-teplate.php' ).

Have you tried running the script within the document ready event like the following code below?
<script>
jQuery(document).ready(function($){
$(function () {
App.dialogs.afterPetitionCreate();
});
});
</script>
The .ready event occurs when the object of the document or the DOM is loaded which makes it perfect to place all of your jquery events and other functions.

This is the code I ended up writing, and does exactly what I want. Like Submit Parkash mentioned, jQuery needs to be used instead of $.
/*
* Adds a single bit of Javascript to the page.
*/
function theme_embed_script($script) {
add_action('wp_footer', function ($script) {
echo '<script type="text/javascript">' . $script . '</script>';
}, 10);
do_action('wp_footer', $script);
}
Usage:
<?php theme_embed_script('jQuery(function () { alert("Hello"); });'); ?>
OR use Wordpress' wp_add_inline_script() script like David mentioned.

Related

update checkout after adding product

am trying to do somthing like : Woocommerce update checkout ajax! am building a multistep form for my client where the customer is adding a product in the cart using ajax . I need to update the checkout when a product is added into the cart . I tried to do an onclick function so when the user add the product in the cart the checkout step update without refreshing the page :
jQuery('#test').on('click',function(){
$( document.body ).trigger( 'update_checkout' );
})
but its not working and i feel like am missing somthing obvious .... Any tips ? :)
This event fire after checkout update
jQuery( document ).on( 'updated_checkout', function() {
//Write code here to fire event
console.log('run');
});
Your code is correct you have to replace $ with jQuery
//Paste this code in theme footer.php file and check it on checkout page
<?php if (is_checkout()) { ?>
<button id="test">Click here to update checkout</button>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#test').on('click',function(){ alert("pp");
jQuery( document.body ).trigger( 'update_checkout' );
});
});
</script>
<?php } ?>
The code is tested everything is working fine.

How to clear form input on page load woocommerce checkout

I am offering customers a repurchase on the order confirmed page. If they click the link they are sended directly to the checkout page. However, the form is then prefilled with the previous data. I would like to clear it, because the idea is one product(ticket) per person.
So far i have the following (and in the page source i can see the script is loaded):
function print_script() {
if (isset($_GET['extrapersoon']) && is_page(21560)){
echo '<script>
window.addEventListener("load", function(){myFunction()};
function myFunction() {
document.getElementsByClassName("woocommerce-checkout").reset();
}
</script>';
}
}
add_action('wp_print_scripts', 'print_script');
I tried other triggers too, such as window.load but no result yet.
Anyone?
You should put the script in the footer using add_action( 'wp_footer', 'print_script' ); to make sure the form gets cleared after the data was loaded into it.
Wordpress has jQuery on default, so I'm using it to look for all the forms in the document and clear them. The function is automatically called on page load, therefore no need for a event listener.
<?php
function print_script() {
if (isset($_GET['extrapersoon']) && is_page(21560)) { ?>
<script type="text/javascript">
( function( $ ) {
$('form').each(function() { this.reset() });
}( jQuery ) );
</script>
<?php }
}
add_action( 'wp_footer', 'print_script' ); ?>

How to add a nonce to an inline script in WordPress

I'm trying to add a nonce to the inline scripts inserted in WordPress by wp_add_inline_script and wp_localize_script, but I can't figure out how to do it. It looks there are no WordPress filters for that. My goal is to have a nonce for inline scripts, so I can define a Content Security Policy that would not break common plugins that insert inline scripts. At the end the result should be something that looks like:
<script type="text/javascript" nonce="xxxxxxxxxx">....</script>
where xxxxxxxx is the nonce.
Do you have any ideas?
As the HTML for inline scripts are generated by the WordPress code
sprintf( "<script type='text/javascript'>\n%s\n</script>\n", ... )
you cannot add an attribute to the HTML script element using wp_add_inline_script() as <script type='text/javascript'> is hard coded.
However, the filter 'script_loader_tag' will allow you to change the HTML for script elements just before it is outputted by WordPress.
Note that the filter 'script_loader_tag' will not be applied to script elements added by calling wp_localize_script() since these are outputted by the WordPress code:
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";
Since these are echoed and <script type='text/javascript'> is hard coded you cannot add an attribute to the HTML script elements of wp_localize_script().
Try to use wp_enqueue_scripts hook
function my_special_inline_script() {
?>
<script>
// your JS code
</script>
<?php
}
add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );
or
function theme_prefix_enqueue_script() {
wp_add_inline_script( 'jquery', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );
Bit late to the party but I just faced this exact problem for the same reasons.
I solved it for wp_add_inline_script by a bit of simple str_replace action.
add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );
function add_nonce_to_script_tag( $tag, $handle, $src ) {
// Check the $handle and respond accordingly
if ( $handle === 'my-script' ) {
$nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
$replace = sprintf("javascript' nonce='%s'>", $nonce_value );
$tag = str_replace( "javascript'>", $replace, $tag);
}
return $tag;
}
// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');
Once the inline script loads, I am seeing the script tag output with a nonce attribute. This is working fine with my Content-Security-Policy.
Check this out
"WordPress 5.7 adds a handful of new functions that enables passing attributes, such as async or nonce"

wp_footer action hook generating error in my WordPress files

I am using beaver builder theme and beaver builder plugin, currently I am creating a new module my own and trying to send all my script code to footer for that my code looks like shown below:
<?php function gt_footer_script(){?>
<script>
jQuery(document).ready(function($) {
"use strict";
if ($('#gt-lightgallery_v<?php echo $gt_filter_counter; ?>').length) {
$('#gt-lightgallery_v<?php echo $gt_filter_counter; ?>').lightGallery({
selector: '.gt-gallery-box',
});
}
});
</script>
<?php } add_action('wp_footer', 'gt_footer_script');?>
my function is gt_footer_script but once I run my code it says can't re-declare function gt_footer_script its already declared on line number 110, while its first function created i am otherwise i have never used this function ever or in my current plugin but still having issue in running my code.
You should just check it's already loaded once. Your plugin probably loads these actions when it's called and then load again your function when it calls your module. Like :
<?php
// We check first if the function wasn't declared earlier :
if(!function_exists('gt_footer_script')) :
// Then we load it
function gt_footer_script(){
?>
<script>
jQuery(document).ready(function($) {
"use strict";
if ($('#gt-lightgallery_v<?php echo $gt_filter_counter; ?>').length) {
$('#gt-lightgallery_v<?php echo $gt_filter_counter; ?>').lightGallery({
selector: '.gt-gallery-box',
});
}
});
</script>
<?php
}
endif;
// If the function already exists, no issue to run this code :
add_action('wp_footer', 'gt_footer_script');
?>

It is possible to add php to this script in Wordpress?

I use this script to filter posts from single category. I based on tags which generate also a class. It is possible to generate this script by WordPress with all tags from my site?
For example below 2 scripts (now I have 12 scripts of this type):
$(document).ready(function(){
$('tr').show();
$("#aipa").click(function(){
$("tr").show();
$('tr:not(:first)').not(".aipa").slideToggle('fast');
});
});
$(document).ready(function(){
$('tr').show();
$("#ris").click(function(){
$("tr").show();
$('tr:not(:first)').not(".ris").slideToggle('fast');
});
});
Now when I add new tags I must manually add another script:
$(document).ready(function(){
$('tr').show();
$("#next-tag").click(function(){
$("tr").show();
$('tr:not(:first)').not("#next-tag").slideToggle('fast');
});
});
Here's a way to do this. This assumes that you're using the standard blog tag system, and that your variable you're using as your ID and class is the tag's slug. Alter it as needed for your needs.
<?php $tags = get_tags(); ?>
<script>
$(document).ready(function(){
<?php foreach ( $tags as $tag ) { ?>
$('tr').show();
$("#<?php echo $tag->slug; ?>").click(function(){
$("tr").show();
$('tr:not(:first)').not(".<?php echo $tag->slug; ?>").slideToggle('fast');
});
<?php } ?>
});
</script>
This will create a single document ready function, and then generate multiple click functions.

Resources