WordPress

How To Create A Custom Geotag Field On Formidable

In this tutorial we're going to use the Formidable plugin and create a new field type that will use HTML5 geolocation to get the current user location, once we get the user location we're going to display a Google map with a pointer for the longitude and latitude of the user.

formidable-geotag-frontend

We can also make sure we display a map in the admin area so that site admin can view the longitude and latitude pointer on a map of the user location.

formidable-admin-entry

Formidable Plugin

formidable-forms

The Formidable plugin is a very popular free WordPress plugin that allows the admin users to create forms using a drag n drop interface. When the forms are complete you can add them to any page on your WordPress site by using a shortcode to display the form. When the user fills out the form all the values of the form can be seen in the admin area or be emailed to you.

This currently has over 300,000 downloads as includes the following features.

  • Create forms with 7 field types: text, email, url, paragraph text, radio, checkbox, and dropdown
  • Create forms from existing templates or add your own. A contact form template is included.
  • Send unlimited email notifications, including autoresponders to the form submitter
  • Create a single styling template using our visual form styler
  • View form submissions from the back-end
  • Import and export forms with XML
  • Send forms to the trash
  • Generate shortcodes with an advanced shortcode UI
  • Customize the HTML in your form for any layout you would like, or use our CSS classes to arrange your fields
  • Integrate with the one-click reCAPTCHA and Akismet for Spam control
  • Use placeholder default values in form fields that clear when clicked
  • Direct links available for previews and emailing surveys with and without integration with your theme
  • Change the name on the Formidable menu to anything you would like
  • Insert your forms on a page, post, or widget using a shortcode [formidable id=x]
  • Support for bugs. We want it to be perfect!

Download Formidable

Creating The Geotag Field

Luckily for us the developers at Formidable made it very easy for us to create our own custom fields to use on our website you just need to use the following actions and filters.

  • frm_available_fields - Add to list of available fields
  • frm_before_field_created - Set the default options for the field
  • frm_display_added_fields - Show the field in the admin area
  • frm_field_options_form - The form to edit the field options
  • frm_update_field_options - Updating the data in the form field
  • frm_form_fields - How to display the field on the front end
  • frm_display_value - How to display the field in the admin area

Create The Plugin

First we need to create the WordPress plugin that will add the new field type to the formidable plugin.

Create a new folder called formidable-geotag in your plugins directory and add a new file called formidable-geotag.php, at the top of the file we need to add the WordPress plugin comments.

<?php
/**
 * Formidable Geotag Field Plugin
 *
 * Plugin Name:       Formidable Geotag Field
 * Plugin URI:        http://www.example.com
 * Description:       A plugin to add a new Geotag field onto the formidable form plugin
 * Version:           1.0.0
 * Author:            Paulund
 * Author URI:        http://www.paulund.co.uk
 * Text Domain:       text-domain
 */

With the plugin setup we can create the PHP class to create the new field, in the constructor of the class we're going to add all the actions and filters we need to edit the formidable plugin and create our new field.

/**
 * Create the formidable geotag field for the form
 */
class Formidable_Geotag_Field
{
    public function __construct()
    {
        add_filter('frm_available_fields', array($this, 'add_geotag_field'));
        add_filter('frm_before_field_created', array($this, 'set_geotag_options'));
        add_action('frm_display_added_fields', array($this, 'show_geotag_admin_field'));
        add_action('frm_field_options_form', array($this, 'geotag_options_form'), 10, 3);
        add_filter('frm_update_field_options', array($this, 'update_geotag_options'), 10, 3 );
        add_action('frm_form_fields', array($this, 'show_geotag_front_field'), 10, 2);
        add_filter('frm_display_value', array($this, 'display_geotag_field_entry'), 10, 3 );
    }
}
new Formidable_Geotag_Field();

Then we can go through the above functions and add the code to perform the different tasks in the class.

Add New Field Tag

This uses the Formidable filter of frm_available_fields to add the Geotag field to the list of fields with formidable.

The function takes an input of the fields array and adds a new element of geotag.

/**
     * Add the geotag field to the list of fields available
     *
     * @param $fields
     * @return mixed
     */
    public function add_geotag_field($fields)
    {
        $fields['geotag'] = __('Geotag');
        return $fields;
    }

Set Default Options

We can setup the default data that's stored on the field for options such as the label text to use by default on the field, in this example the default label will be Set my location:, for the user to set their location.

For this we get the field data array from the filter, check that we're working on the geotag field type, then add default options to the geotag field.

/**
     * Set the default options for the geotag field
     * 
     * @param $field_data
     * @return mixed
     */
    public function set_geotag_options($field_data)
    {
        if ( $field_data['type'] == 'geotag' )
        {
            $field_data['name'] = 'Geotag';

            $defaults = array(
                'label1' => 'Set my location',
            );

            foreach ( $defaults as $k => $v )
            {
                $field_data['field_options'][ $k ] = $v;
            }
        }

        return $field_data;
    }

Show Field In Admin Area

When you're creating your form in the admin area you will use the drag n drop interface to drop the field onto your form. The following function will create the HTML that's added to the admin area when the field is dropped onto the form. This is just going to check that we're on the geotag field if it is then we just want to add a placeholder to show the admin user this is where the field will be placed on the field.

/**
     * Show the geotag placeholder in the admin area
     * 
     * @param $field
     */
    public function show_geotag_admin_field($field){
        if ( $field['type'] != 'geotag' )
        {
            return;
        }

        $field_name = 'item_meta['. $field['id'] .']';
        ?>

        <div class="frm_html_field_placeholder">
            <div class="howto button-secondary frm_html_field">This is a placeholder for your geotag field.</div>
        </div> 
    <?php
    }

Show Form To Edit Field Options

When the field is dropped onto the form in the admin area you can edit the options on the field such as the label used when displaying the field on the frontend.

For this we want to make a new textbox so that the user can edit the default label used.

/**
     * Display the additional options for the new field
     * 
     * @param $field
     * @param $display
     * @param $values
     */
    public function geotag_options_form($field, $display, $values)
    {
        if ( $field['type'] != 'geotag' ) {
            return;
        }

        $defaults = array(
            'label1' => 'Set my location',
        );

        foreach($defaults as $k => $v){
            if ( ! isset($field[$k]) ) {
                $field[$k] = $v;
            }
        }
        ?>
        <tr><td><label>Label</label></td>
            <td>
                <label for="label1_<?php echo $field['id'] ?>" class="howto">Label</label>
                <input type="text" name="field_options[label1_<?php echo $field['id'] ?>]" value="<?php echo esc_attr($field['label1']); ?>" class="frm_long_input" id="label1_<?php echo $field['id'] ?>"  />
            </td>
        </tr>
        <?php
    }

Update The Options Form Data

With the admin form field created we can now add a function to save the data entered in the form.

/**
     * Update the field options from the admin area
     * 
     * @param $field_options
     * @param $field
     * @param $values
     * 
     * @return mixed
     */
    public function update_geotag_options( $field_options, $field, $values )
    {
        if($field->type != 'geotag')
            return $field_options;

        $defaults = array(
            'label1' => __('Set my location', 'formidable')
        );

        foreach ($defaults as $opt => $default)
        {
            $field_options[ $opt ] = isset( $values['field_options'][ $opt . '_' . $field->id ] ) ? $values['field_options'][ $opt . '_' . $field->id ] : $default;
        }

        return $field_options;
    }

Show Field On Frontend

formidable-geotag-frontend

With the admin area form and saving the data for the form field we can now add the HTML to use on the frontend when the form is displayed.

For the frontend we want the user to click a button, then use the HTML5 GeoLocation API to get the user location, add the longitude and latitude to a textbox and display a Google map with a point at the user's location.

/**
     * Add the HTML for the field on the front end
     * 
     * @param $field
     * @param $field_name
     */
    public function show_geotag_front_field($field, $field_name)
    {
        if ( $field['type'] != 'geotag' )
        {
            return;
        }

        $field['value'] = stripslashes_deep($field['value']);
        ?>
        <button class="getUserLocation" ><?php esc_html_e($field['label1']); ?></button>
        <input type="text" id="field_<?php echo $field['field_key'] ?>" name="item_meta[<?php echo $field['id'] ?>]" value="<?php echo esc_attr($field['value']) ?>" />
        <script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>
        <div id="googleMapFormLocation"></div>
        <script>
            $('.getUserLocation').on('click', function(e)
            {
                e.preventDefault();

                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(successGeotag);
                } else {
                    error('Geo Location is not supported');
                }

                return false;
            });

            function successGeotag(position)
            {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;

                $('.getUserLocation').next().val(lat + ' ' + lng);

                var coords = new google.maps.LatLng(lat, lng);

                var options = {
                    zoom: 15,
                    center: coords,
                    mapTypeControl: false,
                    navigationControlOptions: {
                        style: google.maps.NavigationControlStyle.SMALL
                    },
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("googleMapFormLocation"), options);

                var marker = new google.maps.Marker({
                    position: coords,
                    map: map
                });

                $('#googleMapFormLocation').height(300);
            }
        </script>
        <?php
    }

To learn more about how to use the HTML5 GeoLocation API you should look at one of my previous tutorials.

HTML GeoLocation API

Show Field On Admin Area Entries Page

formidable-admin-entry

When the user fills out the form we can see what they've entered in the admin area, but as we're just storing the longitude and latitude of the user location this information isn't very visual for the admin user so it's nice to show the Google map in the admin area too. Therefore we can change the admin area field to get the longitude and latitude to display the Google map.

/**
     * Add the HTML to display the form in the admin area
     * 
     * @param $value
     * @param $field
     * @param $atts
     * @return string
     */
    public function display_geotag_field_entry( $value, $field, $atts )
    {
        if ( $field->type != 'geotag' || empty( $value ) )
        {
            return $value;
        }

        $latlng = explode(' ', $value);

        if(!empty($latlng[0]) && !empty($latlng[1]))
        {
            $lat = $latlng[0];
            $lng = $latlng[1];

            ob_start();

            ?>
            <div class="geotagValue"><?php echo $value; ?></div>
            <script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>
            <div id="googleMapFormLocation"></div>
            <script>
                var coords = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $lng; ?>);

                var options = {
                    zoom: 15,
                    center: coords,
                    mapTypeControl: false,
                    navigationControlOptions: {
                        style: google.maps.NavigationControlStyle.SMALL
                    },
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById("googleMapFormLocation"), options);

                var marker = new google.maps.Marker({
                    position: coords,
                    map: map
                });

                jQuery('#googleMapFormLocation').height(300);
            </script>
            <?php

            $html = ob_get_contents();
            ob_end_clean();
            return $html;
        }

        return $value;
    }

That's all you need to create a new formidable field to get your user location using HTML5 GeoLocation.

Members of Paulund are able to download the complete plugin, simply login and click the download link at the bottom of the page.

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

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