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!
Related
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?
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);
}
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 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.
I'm trying to write an AJAX request as a WordPress plugin. I initially made the request to an outside non-WP server (where it ran fine) simply for testing because I'm entirely new to developing for WP. I then tried using wp_localize_script and .ajaxurl according to the WP codex, but the only response I'm getting is a '0' from admin-ajax. Here is the plugin code:
imap.php:
<?php
/**
* Plugin Name: JQVMap & ChartJS World Map
* Author: Jesse Dillman
*/
add_action( 'wp_enqueue_scripts', 'enqueue_dependencies' );
function enqueue_dependencies()
{
# Run only on given page
if( !is_page(229) )
return;
# Enqueue styles
wp_enqueue_style( 'jmap-css', plugins_url( '/css/jqvmap.css', __FILE__ ) );
# Register dependencies files
wp_register_script( 'js', plugins_url( '/js/jquery-1.7.2.min.js', __FILE__ ) );
wp_register_script( 'jmap-js', plugins_url( '/js/jquery.vmap.js', __FILE__ ) );
wp_register_script( 'world-js', plugins_url( '/js/jquery.vmap.world.js', __FILE__ ) );
wp_register_script( 'unregions-js', plugins_url( '/js/jquery.vmap.un_regions.js', __FILE__ ) );
wp_register_script( 'regioncolors-js', plugins_url( '/js/region_colors.js', __FILE__ ) );
wp_register_script( 'chart-js', plugins_url( '/js/Chart.js', __FILE__ ) );
# Enqueue custom JS file along with dependencies
wp_enqueue_script(
'start-js',
plugins_url( '/js/start.js', __FILE__ ),
array( 'js', 'jmap-js', 'world-js', 'unregions-js', 'regioncolors-js', 'chart-js' ), // dependencies
false,
true
);
wp_localize_script( 'start-js', 'get_data', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
}
function get_chart_data(){
$region1Pie = array(50, '#ddd', 50, '#dc7d50');
$region2Pie = array(25, '#ddd', 75, '#7a9e89');
$region3Pie = array(75, '#ddd', 25, '#867e40');
$chartData = new stdClass();
$pieData = array();
// Swtich based on region
switch($_REQUEST['region']) {
case 'China':
$pieArray = $region1Pie;
break;
case 'Canada':
$pieArray = $region2Pie;
break;
case 'Brazil':
$pieArray = $region3Pie;
break;
}
for($i=0; $i<count($pieArray); $i+=2) {
$pie= new stdClass();
$pie->value = $pieArray[$i];
$pie->color = $pieArray[$i+1];
$pieData[] = $pie;
}
$chartData->pieData = $pieData;
echo json_encode($chartData);
die();
}
add_action('wp_ajax_get_chart_data', 'get_chart_data');
add_action('wp_ajax_nopriv_get_chart_data', 'get_chart_data');
?>
start.js:
// get pie chart canvas
var pie= document.getElementById("pie").getContext("2d");
jQuery(document).ready(function() {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#fff',
// more config options....
onRegionClick: function(element, code, region)
{
$.ajax(get_data.ajaxurl, {
data: {region: region},
action: 'get_chart_data',
dataType: 'json',
success: function(response) {
new Chart(pie).Doughnut(response.pieData, pieOptions);
}
});
}
});
});
When running correctly outside of WP, this renders a world map that displays a pie chart using different data tables depending on where the user clicked. It uses ChartJS and JQVMaps. Again, I'm new to using AJAX in WordPress. Am I using localize_script incorrectly, or is there another problem with how I've implemented the WP admin-ajax?
Get rid of the
action: 'get_chart_data',
in your AJAX call and add it to the data attribute like so...
data: {'region': region, 'action': 'get_chart_data'},
That should get the action being passed into WP so it can get matched to the wp_ajax_get_chart_data action.