I am stuck in strange situation I am trying to pass PHP variable in JS by WordPress wp_localize_script and try to show it in console.log but it is outputting null. here is my code in functions.php
$conv = 1.36;
echo $conv;
add_action('wp_enqueue_scripts','cassets');
function cassets(){
wp_enqueue_script("all-script",get_template_directory_uri().'/all-script.js',array('jquery'),'',true);
$rate= array(
'conv' => $conv,
);
wp_localize_script( 'all-script', 'rate', $rate);
}
and in all-script.js
var conv = rate.conv;
console.log(conv);
In console window it shows null but php echo value shows right.
Thanks in advance.
You're using your $conv variable out of scope. Take a look at PHP's Variable Scope documentation. You're defining $conv in the global scope, but referencing a local scope $conv in your cassets() function.
You need to use the function scoped $conv, either by defining it inside, or passing it to the function as a global variable or pass it as a Reference.
Here's a few examples:
Defining within the scope:
add_action('wp_enqueue_scripts','cassets');
function cassets(){
$conv = 1.36;
wp_enqueue_script( 'all-script', get_template_directory_uri().'/all-script.js', array('jquery'), '', true );
$rate = array(
'conv' => $conv,
);
wp_localize_script( 'all-script', 'rate', $rate );
}
Passing it to the function as a global variable:
$conv = 1.36;
add_action('wp_enqueue_scripts', 'cassets' );
function cassets(){
global $conv;
wp_enqueue_script( 'all-script', get_template_directory_uri().'/all-script.js', array('jquery'), '', true );
$rate = array(
'conv' => $conv,
);
wp_localize_script( 'all-script', 'rate', $rate );
}
Passing it via closure:
$conv = 1.36;
add_action('wp_enqueue_scripts', function() use($conv){
wp_enqueue_script( 'all-script', get_template_directory_uri().'/all-script.js', array('jquery'), '', true );
$rate = array(
'conv' => $conv,
);
wp_localize_script( 'all-script', 'rate', $rate );
});
Your problem is, that you defined $conv outside your function.
Inside your function $conv was is undefined. (I think u should get a warning from php too).
Try this:
add_action('wp_enqueue_scripts','cassets');
function cassets(){
$conv = 1.36;
wp_enqueue_script("all-script",get_template_directory_uri().'/all-script.js',array('jquery'),'',true);
$rate= array(
'conv' => $conv,
);
wp_localize_script( 'all-script', 'rate', $rate);
}
Related
The wp_enqueue_script operates fine as a stand alone script in the main function file. However, when this is placed inside a loop_start function (isolated to run on a specific page), the javascript it calls does not load. Both the 'page name' and post ID work in is_page( ) validated by $message.
add_action( 'loop_start', 'run_on_config_page' );
function run_on_config_page() {
if ( is_page( 1885 ) ) {
function config_scripts() {
wp_enqueue_script( 'config_scripts', get_stylesheet_directory_uri() . '/js/myscript.js', array( 'jquery' ) , '0.0.1', time(), true );
}
add_action( 'wp_enqueue_scripts', 'config_scripts' );
// $message = "Load Script Here";
// echo "<script type='text/javascript'>alert('$message');</script>";
}
}
You are doing it wrong. Use this code to fulfill your requirement.
function config_scripts() {
if( is_page( 1885 ) ){
wp_enqueue_script( 'config_scripts', get_stylesheet_directory_uri() . '/js/myscript.js', array( 'jquery' ) , '0.0.1', time(), true );
}}
add_action( 'wp_enqueue_scripts', 'config_scripts' );
I have done this before but for some reason its dying now. Why? My plugin's index.php has:
add_shortcode('idealformNG', 'func_idealform');
function func_idealform($attr)
{
$args = shortcode_atts( array(
'pageid' => '',
), $attr );
// ----- enqueue required assets ----->>
wp_enqueue_style('styles', plugins_url('public/css/styles.css', __FILE__));
wp_enqueue_script('cookie', 'public/js/js.cookie.min.js', [], '1.0', true);
wp_enqueue_script('serialize', 'public/js/jquery.serializejson.js', [], '1.0', true);
add_action('wp_enqueue_scripts', 'enqueue_assets');
function enqueue_assets($args)
{
global $post;
if($post->ID === intval($args['pageid']))
{
wp_localize_script( 'styles', 'cookie', 'serialize', 'ng_data', array(
'builderURL' => 'http://google.com',
) );
}
}
enqueue_assets($args);
// ----- /enqueue required assets ----->>
}
and in my plugin JS I simply have:
console.log(ng_data.builderURL);
which errs as: Uncaught ReferenceError: ng_data is not defined.
Any ideas why anyone?
The function code below outputs a referral to a javascript file called addons.min.js I believe this is done in line 6 of the code.
Because I don't want to edit the plugins core addons.min.js file I have created my-custom-addons.min.js file and added it to the wp-footer (via wp_enqueue_script).
All good but I can't remove the original referral.
I tried to use
// Remove plugins core addons.min.js
function iw_wcpa_script_remove() {
if ( is_product() ) {
wp_dequeue_script( 'woocommerce-addons' );
wp_deregister_script( 'woocommerce-addons' );
}
}
add_action( 'wc_quick_view_enqueue_scripts', 'iw_wcpa_script_remove', 99 );
// Add custom addons.min.js
function iw_wcpa_script_add() {
if ( is_product() ) {
wp_enqueue_script( 'iw-woocommerce-addons', get_site_url() . '/wp-content/uploads/iwebbers/js/addons.min.js' );
}
}
add_action( 'wp_footer', 'iw_wcpa_script_add' );
But addons.min.js still keeps coming up in my HTML output like this:
<script type='text/javascript' src='https://iwebbers.com/wp-content/plugins/woocommerce-product-addons/assets/js/addons.min.js'></script>
I'm completely in the dark here how to get this done.
Anyone?
If it helps, here's the live page to see the whole HTML source:
https://iwebbers.com/samenstellen/gratis-website-pakket
And just to be clear, I can't edit the function below because it's plugins core.
public function addon_scripts() {
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting' . $suffix . '.js', array( 'jquery' ), '0.4.2' );
wp_enqueue_script( 'woocommerce-addons', plugins_url( basename( dirname( dirname( __FILE__ ) ) ) ) . '/assets/js/addons' . $suffix . '.js', array( 'jquery', 'accounting' ), '1.0', true );
Try to hook wp_enqueue_scripts instead of wp wp_footer with the high priority value:
add_action( 'wc_quick_view_enqueue_scripts', 'iw_wcpa_custom_script', 99 );
UPDATE
replace wocoomerce-addons with woocommerce-addons in your iw_wcpa_script_remove
Try this:
function remove_product_addons_js() {
wp_dequeue_script( 'woocommerce-addons' );
}
add_action( 'wp_print_footer_scripts', 'remove_product_addons_js', 0 );
I am working on a USA map with states to show which states have available properties by changing the color of the state.
I am using Leaflet for the map and have used the Interactive Choropleth Map (https://leafletjs.com/examples/choropleth/) as a basis to build this.
I have added "availability":"2" to the us-states.js file, this is where the number of properties will be shown. I would like to insert a php query
into the .js file to pull the number of properties for that state. Here is a sample from the us-states.js file so that you can see the layout:
{"type":"Feature","id":"02","properties":{"name":"North Carolina","availability":"2"},"geometry":{"type":"MultiPolygon","coordinates":[[[[-131.602021,55.117982],
And I am using this to change color:
// get color depending on population density value
function getColor(d) {
return d > 1 ? '#e1cb7f' :
'#173e34';
}
function style(feature) {
return {
weight: 2,
opacity: 1,
color: 'white',
dashArray: '',
fillOpacity: 1.9,
fillColor: getColor(feature.properties.availability)
};
}
This is my php query:
<?php $count = array('post_type' => 'property', 'meta_key' => 'state', 'meta_value' => 'NC'); $myquery = new WP_Query($count); ?>
and I have tried to add this to the js file, but it will not work:
"availability":"<?php echo json_encode($myquery->found_posts) ?>"
If I manually add the number of properties to the us-states.js file the color does change on the map, so the color change part is working, I just cannot get the php to work in the .js file.
Here is my webpage: https://www.thekeithcorp.com/interactive-map/
Any help would be appreciated!
What you are looking for is wp_localize_script
Execute the query
Register the script using wp_register_script
Localize the registered script with the result of the query using wp_localize_script
Enqueue the script using wp_enqueue_script which references the JavaScript array that WordPress adds before the registered script
on WordPress, can pass variables to JS, eg. with the theme's functions.php:
function localize() {
$items = WP_Query ...
wp_register_script( 'custom', get_template_directory_uri() . '/js/scripts.js', array('jquery'), false, true );
$script_vars = ["features" => []];
for($i=0; $i < $items.size(); $i++) {
array_push($script_vars['features'], (object) array(
"id" => 2,
"type" => "Feature",
"properties" => (object) array(
"name" => "North Carolina",
"availability"=> 2
),
"geometry" => (object) array(
"type" => "MultiPolygon",
"coordinates"=> [ ... ]
)
));
}
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'custom' );
wp_localize_script('custom', 'script_vars', $script_vars);
}
if( !is_admin()) {
add_action("wp_enqueue_scripts", "localize", 10);
}
while you just could change the file-name suffix from .js to .php ...however, when integrating the map with WordPress posts, it's better to localize or to use WP AJAX for loading the data asynchronously - or even cache the HTML output, which may not change that much, except when something is being added.
I got this to work using this in the functions file:
wp_register_script( 'scount', get_template_directory_uri() . '/assets/js/us-states.js' );
// Localize the script with our data that we want to use
$args = array(
'post_type' => 'property',
'fields' => 'ids',
'meta_query' => array(
array(
'key' => 'state',
'value' => 'NC'
)
)
);
$results = new WP_Query($args);
$completed = count($results->posts);
wp_localize_script( 'scount', 'completed', $completed );
// The script can be enqueued now or later.
wp_enqueue_script( 'scount' );
And using this in the json file:
( JSON.stringify(completed) )}
Note there is no ";" at the end!
I have learned to include scripts the following way.
add_action( 'wp_enqueue_scripts', 'woomps_ajax_frontend' );
function woomps_ajax_frontend() {
wp_enqueue_script( 'woomps_sub_slider', plugins_url( '/js/woomps-ajax-frontend.js', dirname(__FILE__)) , array('jquery'), '1.0', true );
$parameters = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'woomps_sub_slider', 'subpost', $parameters);
}
This should fire of my jQuery:
jQuery( document ).on( 'click', '.button_sub_chooser', function() {
alert("test");
jQuery.ajax({
url : subpost.ajax_url,
type : 'post',
data : {
action : 'woomps_update_subscription_chooser',
},
success : function( response ) {
jQuery('#button_sub_chooser').effect( "bounce", "slow" );
}
});
return false;
})
When this is clicked:
<a id="button_shake" class="button_sub_chooser" '.$woomps_ajax_url.'>VElg denne</a>
But wp_enqueue_scripts does not fire of the jQuery. If i just call the function like this woomps_ajax_frontend() it will fire. Why does it work when called like a function and not through wp_enqueue_scripts?
Can you please try this plugin_dir_url(__FILE__) insted of plugins_url().
add_action( 'wp_enqueue_scripts', 'woomps_ajax_frontend' );
function woomps_ajax_frontend() {
wp_enqueue_script( 'woomps_sub_slider', plugin_dir_url(__FILE__). 'js/woomps-ajax-frontend.js' , array('jquery'), '1.0', true );
$parameters = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'woomps_sub_slider', 'subpost', $parameters);
}
The PHP code was put in an included (required_once) file which i had enqueue the following way.
function woomps_scripts() {
require_once ('includes/woomps-ajax-sub-chooser.php');
} //END woomps_scripts
add_action('wp_enqueue_scripts','woomps_scripts');
If I put the require_once ('includes/woomps-ajax-sub-chooser.php'); outside this function woomps_scripts it got included.
So it seems I cant do wp_enqueue_scripts two times down.