Using dynamically created Javascript from WordPress plugin

Using dynamically created Javascript from WordPress plugin © Svilen Milev/sxc.hu

There are many different plug-ins available for wordpress. But what when you come in situation that need to develop plugin that have to use dynamically created Javascript in header that is recreated every time page opens?That option could, for example, be implemented in some Google maps plug-in that shows current visitor locations on map and reads data about locations from web service generated XML.

I this particular case, we want to add our map to wordpress page of our choice inserting ‘{dof_google_map}’ text on the place we want to show our map.

So, for this case, we will use: add_filter(‘the_content’, ‘renderMap’);
in our plug-in to insert our map and function renderMap will replace ‘{dof_google_map}’ with our map container div and also, we could add some HTML if needed on that page. For example purposes, we added a button to trigger Javascript that generates map inside container div named: ‘map_canvas’.

<?php
 
/*
  Plugin Name: Test site Locations Google Map
  Plugin URI: http://www.surgeworks.com
  Description: Plugin that shows live data map of visitors currently on site testsite.com
  Version: 1.0
  Author: Darko Goleš
  Author URI: https://inchoo.net/author/darko.goles/
  License: All rights reserved.
 */
define('DVO_LOCATIONS_PLUGIN_PATH', dirname(__FILE__));
define('DVO_LOCATIONS_PLUGIN_URL', get_option('siteurl') . '/wp-content/plugins/' . basename(DVO_LOCATIONS_PLUGIN_PATH));
//Adding filter into content
add_filter('the_content', 'renderMap');
 
//Function that replaces '{dof_google_map}' string with container div for our map
function renderMap($content) {
    $strtoreplace = "{dof_google_map}";
    $outputtext = '';
    //TODO: remove this button later and implement that call in 'body onLoad()'
    $outputtext .='<button type="button" onclick="init_map()"> This is test button. Click me to see the map!</button>';
    //TODO: Make dimensions to enter from wp-admin and not from here
    $outputtext .='<div id="map_canvas" style="width: 570px; height: 500px; z-index:100;"></div>';
    $content = str_ireplace($strtoreplace, $outputtext, $content);
    return $content;
}

The Javascript function init_map() is located in separate file that is included in header of the page.

How it is included? It is necessary to include it only on Map page and not in other pages of the site, so Javascript will not be added unnecessarily on each but just where needed.

//Filter that help putting Javascript in header
add_filter('the_posts', 'add_script_in_header'); // the_posts gets triggered before wp_head
 
//Function that decides to put our Javascript in header only on page with map
//not to insert in other pages
function add_script_in_header($posts) {
    if (empty($posts))
        return $posts;
    $shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued
    foreach ($posts as $post) {
        if (stripos($post->post_content, 'dof_google_map') > 0) {
            $shortcode_found = true;
            break;
        }
    }
    if ($shortcode_found) {
        //TODO: Need to put google api key on wp-admin side
        $google_maps_url = 'http://maps.google.com/maps?file=api&amp;v=2&amp;key=' . get_option('dvolocgmap_gapikey') . '&sensor=false';
        wp_enqueue_script('google_maps_script',$google_maps_url );
        wp_enqueue_script('script-to-generate-map', DVO_LOCATIONS_PLUGIN_URL . '/lib/script.php');
    }
    return $posts;
}

You may ask: where is our Javascript included in header that generates google map?

Because that Javascript needs to be dynamically generated depends of locations of visitors every time, I put it in php file and named it script.php, but in beginning of the file put:

“Header(“content-type: application/x-javascript”);”

script.php

<?php
Header("content-type: application/x-javascript");
/*
 * Autor: Darko Goleš
 * Script that connects to Google API and preparing Javascript to be included in header of wordpress page
 */
require_once dirname(__FILE__) . '/MapRenderer.php';
//New instance of map renderer
$map_renderer = new MapRenderer();
//Load functional javascript with locations data inside
//Map renderer class reads from XML and generate Javascript for each visitor location like this:
//$generatedJavascript .= 'var latlng = new GLatLng(' . $item->lat . ',' . $item->lon . ');' . "\n";
//$generatedJavascript .= 'map.addOverlay(createMarker(latlng,' . $item->id . ',null));' . "\n";
$locations_generating_script = $map_renderer->getMapJavascript();
 
$script = <<<EOD
/* <![CDATA[ */
    function init_map() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
       map.setCenter(new GLatLng(0, 0), 2);
 
        map.setUIToDefault();
 
        // Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
 
        // Creates a marker whose info window displays the letter corresponding
        // to the given index.
        function createMarker(point, index, dto) {
          var letter = String.fromCharCode("A".charCodeAt(0) + index);
          var letteredIcon = new GIcon(baseIcon);
          letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
          markerOptions = { icon:letteredIcon };
          var marker = new GMarker(point, markerOptions);
 
          GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml("<b> (" + letter + ")</b><br/>"
                    +"Address: "+dto.address+"<br/>"
                    +"Name: "+dto.firstname+" "+dto.lastname+"<br/>"
                    +"email: " + dto.email+"<br/>"
                    );
          });
          return marker;
        }
        $locations_generating_script // here is our dynamically generated javascript from locations.xml file
      }
    }
 
/* ]]> */
EOD;
//Finally echo our dynamic javascript
echo $script;

I hope that this tutorial will be helpful with idea of using Javascript from wordpress plug ins.

You made it all the way down here so you must have enjoyed this post! You may also like:

Extending Pimcore with plugins Zoran Salamun
Zoran Salamun, | 9

Extending Pimcore with plugins

Magicento – PhpStorm plugin for Magento development Zvonimir Buric
Zvonimir Buric, | 13

Magicento – PhpStorm plugin for Magento development

TWIG with wordpress part2 Darko Goles
Darko Goles, | 9

TWIG with wordpress part2

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.