Gravity Forms - Enqueue JS when form embedded? - javascript

I want to be able to only enqueue certain JavaScript when there is a form embedded (emedded with shortcode and php).
Is there an action hook for Gravity Forms that triggers when a form is embedded? Then I could do something like this.
add_action('some_gforms_hook', function() {
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( 'postcode', get_bloginfo('stylesheet_directory') . '/modules/Postcode/assets/js/postcode.js', array('jquery') );
wp_localize_script( 'postcode', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
});
});
If there is no such hook, is there another (non hacky) way of archiving what I want?

You're looking for gform_enqueue_scripts. It passes the $form object so you determine if your scripts should be loaded for the given form.

I found this example in the documentation.
add_action( 'gform_register_init_scripts', 'gform_format_money' );
function gform_format_money( $form ) {
$script = '(function($){' .
'$('.gf_money input').each(function(){' .
'$(this).val(gformFormatMoney($(this).val()));' .
'}).change(function(){' .
'$(this).val(gformFormatMoney($(this).val()));' .
'});' .
'})(jQuery);';
GFFormDisplay::add_init_script( $form['id'], 'format_money', GFFormDisplay::ON_PAGE_RENDER, $script );
}
The problem with this example is that I don't like the JS written in my PHP files and the add_init_script() function needs a string with JS as argument.
I could use file_get_contents() to get the JS from the file but then I will not be able to localize the script for injecting the AJAX url.
I now use the hook as in the question and it works perfect.
add_action( 'gform_register_init_scripts', function() {
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script( 'postcode', get_bloginfo('stylesheet_directory') . '/modules/Postcode/assets/js/postcode.js', array('jquery') );
wp_localize_script( 'postcode', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
});
});

Related

CDN scripts not enqueuing in WordPress

I'm trying to enqueue scripts & styles from CDN in Wordpress so I can use this JSfiddle within the footer of my code:
https://jsfiddle.net/wcepbL45/
I can see the 6 scripts are loading in my Page Source, but the JSfiddle I'm trying to embed in the footer isn't working.
I am guessing some of the new scripts are clashing with the original ones, or do I need to be enqueuing these in my footer.php file?
So atm, my functions.php has this code:
<?php
function load_stylesheets()
{
wp_register_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css',
array(), false, 'all');
wp_enqueue_style('bootstrap');
wp_register_style('style', get_template_directory_uri() . '/style.css',
array(), false, 'all');
wp_enqueue_style('style');
}
add_action('wp_enqueue_scripts', 'load_stylesheets');
function include_jquery()
{
wp_deregister_script('jquery');
wp_enqueue_script('jquery', get_template_directory_uri() . '/js/jquery-3.1.3.min.js', '', 1, true);
add_action('wp_enqueue_scripts', 'jquery');
}
add_action('wp_enqueue_scripts', 'include_jquery');
function loadjs()
{
wp_register_script('customjs', get_template_directory_uri() . '/js/scripts.js', '', 1, true);
wp_enqueue_script('customjs');
}
add_action('wp_enqueue_scripts', 'loadjs');
// Next 6 styles are new (I can see them when i view page source, but I think they are clashing with something, as the JSfiddle I'm trying to input isnt working.
wp_register_style( 'Bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );
wp_enqueue_style('Bootstrap');
wp_register_style( 'Bootstrap_Theme', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css' );
wp_enqueue_style('Bootstrap_Theme');
wp_register_style( 'Bootstrap_Slider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.8.0/css/bootstrap-slider.min.css' );
wp_enqueue_style('Bootstrap_Slider');
wp_register_script( 'jQuery', 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', null, null, true );
wp_enqueue_script('jQuery');
wp_register_script( 'Bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', null, null, true );
wp_enqueue_script('Bootstrap');
wp_register_script( 'Bootstrap_Slider', 'https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.8.0/bootstrap-slider.min.js', null, null, true );
wp_enqueue_script('Bootstrap_Slider');
//
Where am I going wrong?
Multiple mistakes here, You should restrict the use of your scripts to everything but the admin panel. You're not checking if the CDN is actually working, and you have no fallback. get_template_directory_uri() should not be used for the loading the style.css file, instead use get_stylesheet_uri(). You're using multiple functions for no reason and loading. your call for wp_register_style and wp_register_style are outside any functions.
I will just paste what i'm using to load and enqueue scripts and style, feel free to copy pasta! Hope this will help you, don't forget to thumbs up the answer if it does.
<?php add_action( 'wp_enqueue_scripts', 'theme_scripts' );
function theme_scripts() {
if ( ! is_admin() ) {
/**
* Register then enqueue bootstrap bundle js (Bootstrap 5.x required)
*
* Check if CDN's url is valid, if not return fallback
*/
$test_bootstrap_bundle_js = #fopen( 'https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.bundle.min.js', 'r' );
if ( $test_bootstrap_bundle_js !== false ) {
wp_register_script( 'bootstrap_bundle_js', '//stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.bundle.min.js' );
} else {
wp_register_script( 'bootstrap_bundle_js', get_template_directory_uri() . '/assets/js/bootstrap.bundle.min.js' );
};
wp_enqueue_script( 'bootstrap_bundle_js' );
/**
* Register then enqueue bootstrap css (Bootstrap 5.x required)
*
* Check if CDN's url is valid, if not return fallback
*/
$test_bootstrap_css = #fopen( 'https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css', 'r' );
if ( $test_bootstrap_css !== false ) {
wp_register_style( 'bootstrap_css', '//stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css' );
} else {
wp_register_style( 'bootstrap_css', get_stylesheet_uri() . '/assets/css/bootstrap.min.css' );
};
wp_enqueue_style( 'bootstrap_css' );
/**
* Register then enqueue style css
*/
wp_register_style( 'style_css', get_stylesheet_uri(), array( 'bootstrap_css' ) );
wp_enqueue_style( 'style_css' );
};
}; ?>
EDIT 1: Read more about the wp_enqueue_script # https://developer.wordpress.org/reference/functions/wp_enqueue_script/
EDIT 2: Bootstrap 5 as a range plug and play component # https://v5.getbootstrap.com/docs/5.0/forms/range/ (same for Bootstrap 4)
EDIT 3: When you enqueue your scripts you can set up dependencies restricting the load and enqueue of your script
<?php
/**
* Register then enqueue script js
*/
wp_register_script( 'script_js', get_template_directory_uri() . '/assets/js/script.js', array( 'bootstrap_bundle_js', 'jquery_js' ) );
wp_enqueue_script( 'script_js' ); ?>
Inside the wp_register_script we specify an array of script to load our new script after array( 'bootstrap_bundle_js', 'jquery_js' ). It uses the handles defined upon registering the style/script wp_register_script( 'script_js', ... here 'script_js' is the handle.
In response to your last comment, we can do something like this:
For your JS scripts:
(1) jquery.min.js,
eg: wp_enqueue_script( 'jquery_js', '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' );
(2) bootstrap.min.js with dependency towards (1),
eg: wp_enqueue_script( 'bootstrap_js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array( 'jquery_js' ) );
(3) bootstrap-slider.min.js with dependency towards (1) & (2),
eg: wp_enqueue_script( 'bootstrap_slider_js', '//cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.8.0/bootstrap-slider.min.js', array( 'jquery_js', 'bootstrap_js' ) );
(4) script.js with dependency towards (1) & (2) & (3),
eg: wp_enqueue_script( 'script_js', get_template_directory_uri() . '/assets/js/script.js', array( 'jquery_js', 'bootstrap_js', 'bootstrap_slider_js' ) );
For your CSS scripts:
(1) bootstrap.min.css, eg: (same here but with wp_enqueue_style)
(2) bootstrap-slider.css with dependency towards (1),
(3) style.css with dependency towards (1) & (2),

Wordpress: How to load javascript in plugin when only the hostname exists

I have a series of plugins that only load their respective javascript files, based on a page name, as follows:
function getnames_scripts() {
global $post;
if ( in_array( $post->post_name, array( 'somepage', 'anotherpage') ) ){
wp_enqueue_script(
'getnames-script',
plugin_dir_url(__FILE__) . "assets/getnames.js",
array('jquery'),
'1.0',
true
);
}
}
How can I check to load the javascript when only the hostname is present, i.e. 192.0.0.50, instead of 192.0.0.50/somepage/?
if($_SERVER['HTTP_HOST']=='192.0.0.50'){
// wow man
}else{
// Oh man
}

Wordpress: jQuery/JavaScript in plugin only works when logged in

What code exactly do I need to incorporate into my plugin to make it function both when logged in, and logged out?
function getdetailedsearchresults_scripts() {
global $post;
$temp = $_SERVER['HTTP_HOST'];
if (in_array($post->post_name, array('detailed-search-results', 'detailed-gym-gw', 'detailed-gyms-page')) || in_array($temp, array('192.0.0.50')) ){
wp_enqueue_script(
'getdetailedsearchresults-script',
plugin_dir_url(__FILE__) . "assets/getdetailedsearchresults.js",
array('jquery'),
'1.0',
true
);
}
wp_localize_script(
'getdetailedsearchresults-script', // this needs to match the name of our enqueued script
'resultsSearchDetailed', // the name of the object
array('ajaxurl' => admin_url('admin-ajax.php')) // the property/value
);
}
add_action( 'wp_enqueue_scripts', 'getdetailedsearchresults_scripts' );
add_action( 'wp_ajax_detailedsearchresults', 'detailedsearchresults_callback' );
add_action( 'wp_ajax_no_priv_detailedsearchresults', 'detailedsearchresults_callback' );
function detailedsearchresults_callback() { }

Enqueue js in wordpress with charset

I have script
<script src="js/app/script.js" charset="iso-8859-1"></script>
I need to enqueue this js in wordpress with charset. How can I do it ?
I tried do it like that
private static function includeScriptWithCharset($path, $charset){
// I need charset="iso-8859-1"
wp_enqueue_script ($path, plugins_url($path). " ". $charset);
}
I know this question is quite old now, however I have the answer for this, in case this still helps Serg, or helps anyone else who comes across this issue.
The way to do this is to use the WordPress 'script_loader_tag' hook as follows:
// First enqueue your scripts as follows:
wp_enqueue_script( 'my-script-handle', get_stylesheet_directory_uri() . '/some.js', array( 'jquery' ), '6.0');
wp_enqueue_script( 'my-other-handle', get_stylesheet_directory_uri() . '/someother.js', array( 'jquery' ), '6.0');
// Next use the script loader hook as follows:
function my_async_scripts( $tag, $handle, $src ) {
// the handles of the enqueued scripts we want to async
$async_scripts = array( 'my-script-handle', 'my-other-handle' );
if ( in_array( $handle, $async_scripts ) ) {
return '<script type="text/javascript" src="' . $src . '" charset="iso-8859-1"></script>' . "\n";
}
return $tag;
}
add_filter( 'script_loader_tag', 'my_async_scripts', 10, 3 );

Can't get Wordpress AJAX working

I have been following multiple tutorials on this (including Wordpress's own) and its driving me a little crazy.
I am trying to get AJAX working on the front end in Wordpress, however it is simply not doing anything, I know the function works as I have tested this independently, your input will be really appreciated on this one. Many thanks in advance.
The code in functions.php
function call_ajax()
{
//assuming this is in a theme?
wp_enqueue_script( 'ajax_car_models', get_template_directory_uri() . '/js/ajax_car_models.js', array( 'jquery' ), null, true);
//loacalize the script using the same handle it was registered / enqueued with
wp_localize_script( 'ajax_car_models', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//make a call to call_ajax at the right time
add_action( 'wp_enqueue_scripts', 'call_ajax' );
add_action( 'wp_ajax_ajax_car_models', 'ajax_car_models' );
add_action( 'wp_ajax_nopriv_ajax_car_models', 'ajax_car_models' );
function ajax_car_models() {
$args = array( 'post_type' => 'product', 'posts_per_page' => 1040 );
$loop1 = new WP_Query( $args );
$code = '';
$car_make = 26;
$all_models = array();
while ( $loop1->have_posts() ) : $loop1->the_post();
$terms_make = get_the_terms( get_the_id(), 'pa_car-make' );
foreach ( $terms_make as $make ) {
if ( $make->term_id == $car_make ) {
$the_car_model = get_the_terms( get_the_id(), 'pa_model' );
foreach ( $the_car_model as $the_model ) {
if ($all_models[$the_model->name] != 'true') {
$code .= '<br />'.$the_model->name.' ';
$all_models[$the_model->name] = 'true';
}
}
}
}
endwhile;
wp_reset_postdata();
header( 'Content-type: application/json' );
echo json_encode( $code );
die();
}
And the jQuery itself:
jQuery( document ).ready(function() {
jQuery('#car-make').change(my_js_function);
function my_js_function()
{
jQuery.ajax({
url: my_ajax_script.ajaxurl,
dataType: 'json', // add this line
data: ({action : 'ajax_car_models'}),
success: function() {
jQuery("#feedback").html(data);
}
});
}
});
If you include you javascript inline you will not be able to use localize pass it the ajax url.
You should move your javascript into a different file and then use wp_enqueue_script in order to properly use ajax.
function call_ajax()
{
//assuming this is in a theme?
wp_enqueue_script( 'ajax_car_models', get_template_directory_uri() . '/js/ajax_car_models.js', array( 'jquery' ), null, true);
//loacalize the script using the same handle it was registered / enqueued with
wp_localize_script( 'ajax_car_models', 'my_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
//make a call to call_ajax at the right time
add_action( 'wp_enqueue_scripts', 'call_ajax' );
You also need to send json headers in your response function
header( 'Content-type: application/json' );
echo json_encode( $code );
exit();
In your ajax call you are not passing the data to your success callback
success: function(data){
console.log(data);
//...
}
You can use the network tab on the chrome developer tools to look at what requests are actually made and check the response they receive.
According to the PHP manual json_encode needs string data to be UTF8 encoded.
Alternatively, you can try doing this instead in your functions.php...
$return_array = array(
'val' => $code
);
echo json_encode($return_array);
Then, in your jQuery script...
jQuery("#feedback").html(data.val);
Also, try adding to your ajax request one more option...
url: my_ajax_script.ajaxurl,
dataType: 'json', // add this line
data: ({action : 'ajax_car_models'}),
Hope these help!

Categories