Paulund http://www.paulund.co.uk Paulund | WordPress, PHP, CSS, HTML5 Sun, 14 Sep 2014 18:15:24 +0000 en-US hourly 1 http://wordpress.org/?v=4.0 HTML5 Download Attribute http://www.paulund.co.uk/html5-download-attribute http://www.paulund.co.uk/html5-download-attribute#comments Fri, 05 Sep 2014 08:24:23 +0000 http://www.paulund.co.uk/?p=10819 In this tutorial we are going to look into another HTML5 feature with the download attribute. The download attribute is a way of telling the browser that to download the file it is linking to, this can be a media file or a PDF document or a webpage etc. This is something you used to have to do with a server-side code. For example you will link to a server-side

The post HTML5 Download Attribute appeared first on Paulund.

]]>
In this tutorial we are going to look into another HTML5 feature with the download attribute.

The download attribute is a way of telling the browser that to download the file it is linking to, this can be a media file or a PDF document or a webpage etc. This is something you used to have to do with a server-side code. For example you will link to a server-side file of force-download.php and pass in an argument of the file you want to download.

<a href="force-download.php?file=download-webpage.html">Download Webpage HTML</a>

Then on the server-side you will have to get the contents of the the requested file and force the browser to download the contents by doing something like this.

function downloadFile($file){
    $file_name = $file;
    $mime = 'application/force-download';
    header('Pragma: public'); 	// required
    header('Expires: 0');		// no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    readfile($file_name);
    exit();
}

Now we can avoid this step and just use the download attribute in the link.

<a href="download-webpage.html" download>Download Webpage HTML</a>

The download attribute isn't currently supported by all browsers currently only Chrome, Firefox and Opera support the attribute the other browsers will treat this just link any other link. Therefore it will just open the document or media file up in the browser, but with browsers that support this new attribute will download the file you are linking to on the user's machine.

To view an up to date version of the current support browsers of the download attribute you can view it on the link below.

Browser Support For Download Attribute

The download attribute is great to use on things like a PDF document if you want people to have this as a hardcopy for something, like a receipt. Instead of just opening it up in the browser you can make the user download it directly.

You can even change the name of the file you are downloading by adding a value to the download attribute like the following example.

<a href="some-random-generated-filename.pdf" download="invoice.pdf">Download Invoice</a>

The post HTML5 Download Attribute appeared first on Paulund.

]]>
http://www.paulund.co.uk/html5-download-attribute/feed 0
HTML5 Form Validation http://www.paulund.co.uk/html5-form-validation http://www.paulund.co.uk/html5-form-validation#comments Wed, 03 Sep 2014 08:09:58 +0000 http://www.paulund.co.uk/?p=10054 Since HTML5 came into webpages it brought a bunch of new features, the most useful features it brings is the functionality that you would normally use JavaScript for. An very good example of how HTML5 can help us with forms is client side form validation. In the past we would create a form on a page and then setup the JavaScript on the OnSubmit event to then check the values

The post HTML5 Form Validation appeared first on Paulund.

]]>
Since HTML5 came into webpages it brought a bunch of new features, the most useful features it brings is the functionality that you would normally use JavaScript for. An very good example of how HTML5 can help us with forms is client side form validation.

In the past we would create a form on a page and then setup the JavaScript on the OnSubmit event to then check the values are how we want them to be. The most common query would be to check that all required fields are not empty.

if(document.getElementById('username').value == '')
{
    alert('Username can not be empty.');
}

If you have a form that has a lot of input boxes then your JavaScript can quickly become huge, all with checks that the form field is a required field. Or you will have to do checks that the value entered is a number, an email address, a telephone number etc. This is where HTML5 comes into it's own, HTML5 comes with some new attributes that you can use to do these type of checks without having to write any JavaScript.

There are 3 new attributes that you need to be aware of in HTML5 form validation the type attribute, pattern and require.

Type Attribute

The type attribute is want you would normally use to define that a form field is a textbox or a checkbox or a radio button.

<input type="text" />
<input type="checkbox" />
<input type="radio" />

With HTML5 it comes with a bunch of new type values that will bring form validation.

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week

Color Input Type

The color input type will add a color picker to your form allowing the user to select a color which will add a HEX value to the input.

<input type="color" />

There is no validation improvements that come with this input type it will just add a color picker to the page.

Date Input Type

The date input type will allow you to add a date picker to your form.

<input type="date" />

The validation that you get with this field can only enter numbers in the input box.

Email Input Type

The email input type will add a new textbox to the browser.

<input type="email" />


The form validation you get with this is that on submit the value must be a valid email address.

Month Input Type

The month input type will add a new textbox to the browser allowing you to pick a month.

<input type="month" />


The validation that you get with this is that it ensures the user can only select a month and year.

Number Input Type

The number input type will add a new textbox to the browser allowing you to pick a single number.

<input type="number" />


The validation that you get with this is that it ensures the user can only enter a number.

Range Input Type

The range input type will add a new slider to the browser allowing you to pick from a range of numbers.

<input type="range" min="1" max="10" />

The validation that you get with this is that it ensures you can only select numbers within a certain range.

Search Input Type

The search input type adds a textbox to the browser which allows you to add a search box to the page.

<input type="search" />

You do not get any new validation features with this input type.

Time Input Type

The time input type will allow you to add a time picker to your form.

<input type="time" />


The validation you get with this is that it allows you to ensure the user can only enter a time.

Url Input Type

The URL input type will add a textbox to the browser which ensures a URL is entered.

<input type="url" />


The validation you get with this is that when the form is submitted the browser checks to see if this value is a URL.

Week Input Type

The week input type adds a date picker to the browser that allows the user to select a week of a year.

<input type="week" />


The validation you get with this is that you ensure the user can only select a certain week.

Pattern Attribute

The pattern attribute allows you to define your own set of rules that the input type must compile to, the rules use regular expression to define what these fields accept.

Only Letters

For example if we want to make sure that the input box only accepts letters then we can use the following code.

<input type="text" pattern="[a-zA-Z]+" title="Only enter letters" />


HEX Values

To ensure that the input box only accepts HEX values you can use the pattern attribute with a regular expression.

<input type="text" pattern="^#+([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" title="HEX Values" />


Required Attribute

The required attribute is the attribute that you will most likely use the most. This attribute ensures that this input box is not empty, placing it on a textbox element will check the value on the submit event and if the value is empty a error message will be displayed.

This attribute is what you will use to replace the JavaScript code example at the start of the tutorial.

<input type="text" required="true" />


Hopefully from the above tutorial you can see all the different ways that you can use the new HTML5 validation rules and how they can help you write less JavaScript validation in your future projects.

The post HTML5 Form Validation appeared first on Paulund.

]]>
http://www.paulund.co.uk/html5-form-validation/feed 0
Free Files For September 2014 http://www.paulund.co.uk/free-files-september-2014 http://www.paulund.co.uk/free-files-september-2014#comments Mon, 01 Sep 2014 19:33:41 +0000 http://www.paulund.co.uk/?p=10992 Each month the Envato marketplace brings you free premium files. Envato is a web marketplace where you can get premium files for different areas of your website. My favourite marketplaces are the script marketplace CodeCanyon and the theme marketplace ThemeForest. Here are the files which you can get for free in September 2014. jQuery Shining Image 177 purchases at the price of $8. jQuery Shining Image is an HTML5 jQuery

The post Free Files For September 2014 appeared first on Paulund.

]]>
Each month the Envato marketplace brings you free premium files.

Envato is a web marketplace where you can get premium files for different areas of your website. My favourite marketplaces are the script marketplace CodeCanyon and the theme marketplace ThemeForest.

Here are the files which you can get for free in September 2014.

jQuery Shining Image

jQuery Shining Image

177 purchases at the price of $8.

jQuery Shining Image is an HTML5 jQuery plugin that add an animated shining effect to your images.

This plugin use canvas element, and is compatible with all computer and mobiles modern browsers. For the others, the image keeps its default static look.

  • Very easy to use : $(‘img’).shiningImage()
  • Many options to customize the effect
  • Can be used with lightbox, using onComplete Event
  • The shining image keeps the default style and class.
  • The shining image keeps original image click, mouseover, mouseout, mouseup and mousedown events
  • Compatibility : IE9+ , Firefox 4+ , Google Chrome 11+, Opera 10.6+, Safari 3.2+

Download For Free

Smarty | Mobile & Tablet Responsive Web Template

Smarty | Mobile & Tablet Responsive Web Template

596 purchases at the price of $10.

Smarty | Mobile & Tablet Responsive Web Template [HTML5, CSS3] which is perfectly designed and developed for your business mobile website. Ready to use HTML pages, Customization is really very easy…

Download For Free

Door Transition

Door Transition

52 purchases at the price of $6.

  • 3 Different Transition
  • Quicktime PNG + Alpha Maximum Quality
  • Full HD (1920 X 1080)
  • All Video Loopable
  • 2 Photo Included (Open_Door.png + Close_Door.png)

Download For Free

Optimized Low Poly Male Human Base Mesh Version1.0

Optimized Low Poly Male Human Base Mesh Version1.0

46 purchases at the price of $8.

This is an optimized 2nd version of generic male low poly base mesh (eyes, teeth & tongue included). Keeping the human muscle anatomy in mind I have maintained low poly, clean topology, all quads & also UV-unwrapped. It has a polycount of only 2980 tris (compared to my older version which has 5924 tris). It is ready for sculpting, texturing, rigging, animation etc.

Download For Free

Same Hexagon

Same Hexagon

23 purchases at the price of $10.

Same Hexagon is a new version of classic Same Game. The goal is to clear out tiles and gain maximum number.

The more tiles you remove, the more score you get. The formula is: n*(n-1).

Easy to modify

Download For Free

Drinking Straws

Drinking Straws

0 purchases at the price of $5.

Brightly coloured drinking straws in many different colours form a multi-coloured background, with shallow focus.

Download For Free

News 1 - Music

AudioJungle

99 purchases at the price of $14.

This is a strong and energetic announcement. Perfect for news, intros, videos and other openings. Here you can hear strings, trumpets, brass, effects and drums.

Download For Free

Framed Mockup

Framed Mockup

56 purchases at the price of $5.

5 Photorealistic framed vintage Mock-ups. Great for logos, invitations, quotes, business cards, flyers, photos and other artwork. Real life photography used. No fake photoshopped backgrounds.

2 Styles each. Either Letterpress your design or blend in full graphic.

Download For Free

The post Free Files For September 2014 appeared first on Paulund.

]]>
http://www.paulund.co.uk/free-files-september-2014/feed 0
Getting Started With Composer In PHP http://www.paulund.co.uk/started-with-composer-php http://www.paulund.co.uk/started-with-composer-php#comments Sat, 30 Aug 2014 07:25:45 +0000 http://www.paulund.co.uk/?p=9833 In this tutorial we are going to learn about composer and how we can use it to develop our PHP applications. Composer is a tool that allows to manage your third party dependencies in your PHP application, it will allow you to create a list of all third party scripts and libraries and their version number. Composer will then look into the repository of the third party library and the

The post Getting Started With Composer In PHP appeared first on Paulund.

]]>
In this tutorial we are going to learn about composer and how we can use it to develop our PHP applications.

Composer is a tool that allows to manage your third party dependencies in your PHP application, it will allow you to create a list of all third party scripts and libraries and their version number. Composer will then look into the repository of the third party library and the current version number and will automatically download the library into your application.

Composer needs to be told exactly what libraries it requires to install per project, it will then install these libraries into a default vendor folder. An advantage of composer is that it allows you to set dependencies on the libraries.

You can also setup composer to just use defined versions or you can use a wildcard on the versions and composer will get the latest version of the library. Therefore running the update script once a day will ensure you have the latest version of the library code.

Installing Composer

Composer requires that you have PHP 5.3.2 or higher installed, when you run through the installation process there will be other PHP settings that you will need to turn on such as the php_openssl extension.

Depending on the repository type you will need different things install, for example if the repository is in GIT then you will need to have GIT installed.

For information on how to install composer on your local machine you can see this on the composer site.

Install Composer

The easiest way to install composer is by downloading it directly.

curl -sS https://getcomposer.org/installer | php

How To Use Composer

To use composer you need to first create the composer.json file with all the dependencies you need in your application. This will be populated with a JSON object of the dependencies that need to be included in the application.

The first thing you need to know about is using the require keyword this tells composer that your application requires this package to run.

{
    "require": {
        "php": ">=5.3.33",
        "zendframework/zendframework": "2.3.*",
    }
}

This tells composer that the application needs to have PHP of 5.3.33 or higher installed and that it requires Zend Framework 2.3.*, using the wildcard will automatically update up until version 2.4.

Once the composer.json file is in the directory you can install the libraries by running the commands.

php composer.phar install

Default Composer Packages

There is a massive list of third party packages that you can use by default with composer, to see if the package that you need is available to use with composer then you can browser for it on Packagist.org.

Packagist

Autoloading Your Dependencies

One of my favourite favourites that you get with composer is the autoload file. Inside the vendor folder there is a created file called autoload.php, if this is included in application then you simply need to instantiate the class of the library and this file will autoload it for you.

require_once 'vendor/autoload.php';

The post Getting Started With Composer In PHP appeared first on Paulund.

]]>
http://www.paulund.co.uk/started-with-composer-php/feed 0
Using AJAX In WordPress http://www.paulund.co.uk/using-ajax-wordpress http://www.paulund.co.uk/using-ajax-wordpress#comments Mon, 25 Aug 2014 07:18:13 +0000 http://www.paulund.co.uk/?p=10707 In the following tutorial we are going to learn how you can use AJAX in WordPress to run your own functions. The way this works in WordPress is by allowing you to attach your own actions that you can access from an AJAX request to change the content on the page. What Is AJAX? Normally on a webpage you have to wait for the server to load the content of

The post Using AJAX In WordPress appeared first on Paulund.

]]>
In the following tutorial we are going to learn how you can use AJAX in WordPress to run your own functions. The way this works in WordPress is by allowing you to attach your own actions that you can access from an AJAX request to change the content on the page.

What Is AJAX?

Normally on a webpage you have to wait for the server to load the content of the web page, after the load the only way you can change the content on the page is with JavaScript code. JavaScript is a client-side language that will not run any server side tasks, therefore you can not make another request to the server to change the content unless you refresh the page, but this could change the content in other areas of the page.

AJAX stands for Asynchronous JavaScript and XML, allowing you to make asynchronous HTTP requests to the server once the page has already loaded. It will use JavaScript to make a request to a URL allowing you to POST additional data to the server, the output of this server request is then processed and stored in the JavaScript so that you can change the content of the page.

WordPress has AJAX already built into the core and requires you to submit this information to a certain URL in the WordPress application, the reason you can't use any URL with WordPress AJAX is because WordPress needs to be instantiated before you can access data in the WordPress database.

AJAX In The Admin Area

If you have previous experience using AJAX, then using it in the WordPress admin area is relatively straight forward. As AJAX is already built into the core you can simply piggy back on this.

First you need to create a JavaScript file that you will use to make the AJAX request and handle the data returned, then enqueue this in the admin screens. Create a WordPress plugin or add the following to your theme functions.php file.

add_action( 'admin_enqueue_scripts', 'add_ajax_javascript_file' );
function add_ajax_javascript_file()
{
    wp_enqueue_script( 'ajax_custom_script', plugin_dir_url( __FILE__ ) . 'ajax-javascript.js', array('jquery') );
}

This will add our JavaScript file to the admin pages in WordPress admin area, now we can add the jQuery required to submit the ajax request.

jQuery(document).ready(function($) 
{
    var data = {
        'action': 'get_post_information',
	'post_id': 120
    };

    $.post(ajaxurl, data, function(response) {
        alert('Server response from the AJAX URL ' + response);
    });
})

The above JavaScript will be added to our JavaScript file and will use jQuery to post data to the ajaxurl variable. This variable is a global variable setup by WordPress that will post to the admin-ajax.php file. This file instantiates WordPress and will run any actions setup in WordPress.

The data that we are submitting is a JavaScript object with the fields action and post_id in it. The action is the WordPress action code we want to run when submitting this request, the other data is also posted so that we can consume this in the server-side code.

Now we need to setup the WordPress action that will get called on this AJAX request.

<?php 

add_action( 'wp_ajax_get_post_information', 'ajax_get_post_information' );

function ajax_get_post_information() 
{
    if(!empty($_POST['post_id']))
    {
        $post = get_post( $_POST['post_id'] );

        echo json_encode( $post );
    }	

    die();
}

The above code should be added to either the new plugin or to the functions.php file so that the action can be registered. We need to use the action of "wp_ajax_{action}" with {action} being the one defined in the JavaScript file. In the callback function we then get the posted post_id and search for the post using the get_post() function, then we can echo a JSON object of the post data for the JavaScript to pick up the response. On the response of the AJAX we can now add this post information to any part of the page we want.

AJAX In The Frontend

AJAX on the frontend of your website is a bit more complicated but is still do-able if you understand the concepts of the above code.

The first thing you need to be aware of is the ajaxurl JavaScript variable is not defined on the frontend so you need to define this namespace object when you load your JavaScript file by using the function wp_localize_script()

add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file' );
function add_frontend_ajax_javascript_file()
{
    wp_localize_script( 'frontend-ajax', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    wp_enqueue_script( 'ajax_custom_script', plugin_dir_url( __FILE__ ) . 'ajax-javascript.js', array('jquery') );
}

In the admin area there is only one AJAX action that you need to use wp_ajax_{action} on the frontend you can use two AJAX actions, wp_ajax_{action} and wp_ajax_nopriv_{action} the difference being that the current user doesn't need to be logged in to run the AJAX action. Therefore if the user isn't logged in it will run the function attached to wp_ajax_nopriv_ but if the user is logged in it will run the function attached to wp_ajax_

<?php 

add_action( 'wp_ajax_get_post_information', 'ajax_get_post_information' );
add_action( 'wp_ajax_nopriv_get_post_information', 'ajax_get_post_information' );

function ajax_get_post_information() 
{
    if(!empty($_POST['post_id']))
    {
        $post = get_post( $_POST['post_id'] );

        echo json_encode( $post );
    }	

    die();
}

AJAX Errors

If the AJAX action fails then it will return one of two values either 0 or -1.

If the action that you are requesting doesn't exist then the AJAX response will return 0. To fix this error you need to make sure that you have defined your wp_ajax_ action correctly.

If the request fails to call the URL correctly it will return with a -1.

The post Using AJAX In WordPress appeared first on Paulund.

]]>
http://www.paulund.co.uk/using-ajax-wordpress/feed 0
Sanitize Special Word Characters With PHP http://www.paulund.co.uk/sanitize-special-word-characters http://www.paulund.co.uk/sanitize-special-word-characters#comments Thu, 21 Aug 2014 16:17:49 +0000 http://www.paulund.co.uk/?p=10827 Anybody who has worked with user content on a website will know the problem you get when a user writes the content in Word and copy and pastes this content into a textarea so that you can store it in the database. The problem that you have is that when you want to display this content on the front-end you will get a lot of strange black question marks. This

The post Sanitize Special Word Characters With PHP appeared first on Paulund.

]]>
Anybody who has worked with user content on a website will know the problem you get when a user writes the content in Word and copy and pastes this content into a textarea so that you can store it in the database.

The problem that you have is that when you want to display this content on the front-end you will get a lot of strange black question marks. This is because some of the characters that Word uses is not recognised by the browser as a valid character.

Things like curly quotes, curly double quotes, hyphens, underscores, ellipsis are all different in Word. Therefore you need to validate these values when before you insert then into the database to allow you to display the content correctly in the front-end.

The following PHP code snippet will first search and replace for the microsoft word special characters and replace them with standard characters. Next we use a preg_replace to remove any non-ascii special characters from the content.

This should clean up the Word characters in the content allowing you to display the content on the browser.

function sanitize_from_word( $content )
{
    // Convert microsoft special characters
    $replace = array(
        "‘" => "'",
        "’" => "'",
        "”" => '"',
        "“" => '"',
        "–" => "-",
        "—" => "-",
        "…" => "&#8230;"
    );
        
    foreach($replace as $k => $v)
    {
        $content = str_replace($k, $v, $content);
    }
        
    // Remove any non-ascii character
    $content = preg_replace('/[^\x20-\x7E]*/','', $content);

    return $content;
}

The post Sanitize Special Word Characters With PHP appeared first on Paulund.

]]>
http://www.paulund.co.uk/sanitize-special-word-characters/feed 0
Add Custom User Fields To User Profile Page http://www.paulund.co.uk/add-custom-user-fields-profile-page http://www.paulund.co.uk/add-custom-user-fields-profile-page#comments Wed, 20 Aug 2014 07:59:32 +0000 http://www.paulund.co.uk/?p=10913 In a previous article I explained how you can modify the contact information on the WordPress User profile page, but what if you want to know more custom information from the user that requires more that just a text field. In this tutorial we are going to look at how we can add new fields to the User profile page to collect custom information that requires a dropdown or checkbox.

The post Add Custom User Fields To User Profile Page appeared first on Paulund.

]]>
In a previous article I explained how you can modify the contact information on the WordPress User profile page, but what if you want to know more custom information from the user that requires more that just a text field.

In this tutorial we are going to look at how we can add new fields to the User profile page to collect custom information that requires a dropdown or checkbox.

There are 4 WordPress actions that we need to use in this tutorial:

  • show_user_profile - Used on the "Your Profile" page.
  • edit_user_profile - Used on the "Edit User" page.
  • personal_options_update - Runs on the page load of the "Your Profile" page, use to process the form submissions.
  • edit_user_profile_update - Runs on the page load of the "Edit User" page, use to process the form submissions.

For this tutorial we are going to use OOP and create a PHP class that will handle this customisation, when working with OOP with WordPress it's best practice to place the add_action() or add_filter() functions in the constructor of the class.

class Add_New_User_Profile_Fields
{
    public function __construct()
    {
        // add actions for the profile customisation
        add_action( 'personal_options_update', array($this, 'update_custom_profile_fields') );
        add_action( 'edit_user_profile_update', array($this, 'update_custom_profile_fields') );

        add_action('show_user_profile', array($this, 'add_custom_profile_fields'));
        add_action('edit_user_profile', array($this, 'add_custom_profile_fields'));
    }

    /**
     * Add new custom fields to the profile page
     *
     * @param $profileuser
     */
    public function add_custom_profile_fields( $profileuser )
    {
        // add new custom profile fields
    }

    /**
     * Update new fields on the user profile page
     *
     * @param $user_id
     */
    public function update_custom_profile( $user_id )
    {
        // code to validate and update the user data
    }
}

To use this in your site you can either turn this into a plugin or include the file from your theme functions.php and instantiate the class.

Add New Fields To Profile Page

To add new fields to the profile pages we need to use the actions show_user_profile and edit_user_profile which will both run the same function add_custom_profile_fields. From here we can simply add any HTML we want to create these new custom form fields.

/**
     * Add new custom fields to the profile page
     *
     * @param $profileuser
     */
    public function add_custom_profile_fields( $profileuser )
    {
        $customData = get_user_meta( $profileuser->ID, 'custom_user_fields', true );
        ?>
        <h2><?php _e('Custom User Profile Fields'); ?></h2>
        <table class="form-table">
            <tr>
                <th><label for="custom_user_fields_textbox"><?php _e('Custom Textbox'); ?></label></th>
                <td><input type="text" name="custom_user_fields_textbox" id="custom_textbox" value="<?php echo if(isset($customData['textbox'])){ echo esc_attr($customData['textbox']); } ?>" class="regular-text" /></td>
            </tr>

            <tr>
                <th><label for="custom_user_fields_select"><?php _e('Custom Select'); ?></label></th>
                <td>
                    <select name="custom_user_fields_select" id="custom_select">
                        <option value="">Please Select</option>
                        <option value="1" <?php if(isset($customData['select'])){ selected($customData['select'], 1); } ?>>Select Value 1</option>
                        <option value="2" <?php if(isset($customData['select'])){ selected($customData['select'], 2); } ?>>Select Value 2</option>
                        <option value="3" <?php if(isset($customData['select'])){ selected($customData['select'], 3); } ?>>Select Value 3</option>
                        <option value="4" <?php if(isset($customData['select'])){ selected($customData['select'], 4); } ?>>Select Value 4</option>
                        <option value="5" <?php if(isset($customData['select'])){ selected($customData['select'], 5); } ?>>Select Value 5</option>
                    </select>
                </td>
            </tr>

            <tr>
                <th><label for="custom_user_fields_checkbox"><?php _e('Custom Checkbox'); ?></label></th>
                <td><input type="checkbox" name="custom_user_fields_checkbox" id="custom_checkbox" value="1" <?php if(isset($customData['checkbox'])){ checked($customData['checkbox'], 1); } ?>/></td>
            </tr>
        </table>
    <?php
    }

First we start off by getting the current values in the database for the user. Like posts, WordPress allows you to store extra information to the users of the application, this is called User meta. When we are saving the data we will need to store this onto the user meta information. Therefore we are going to use the function get_user_meta() to get the custom user fields that we are creating. This will return an array of the custom field data from the database, we will use this data to populate the form.

Next in this code we simply create the form fields in HTML of all the information that we want.

With this code in your class you should be able to go to the profile page and see the new fields towards the bottom of the profile page.

Save Profile Fields

With the fields now on show on the user profile page we need to process this information and save it on to the user meta information.

On the save button of the profile page it will POST the form back to itself and process the values, this is why we can hook into the actions personal_options_update and edit_user_profile_update to process the new User fields.

The below code will check to see if the form field has been posted it will then sanitize the input and store the value in an array. After all the fields are processed into this array we can then take this variable and store it against the user meta using the function update_user_meta().

/**
     * Update new fields on the user profile page
     *
     * @param $user_id
     */
    public function update_custom_profile( $user_id )
    {
        $userData = array();

        if(!empty( $_POST['custom_user_fields_textbox'] ))
        {
            $userData['textbox'] = sanitize_text_field( $_POST['custom_user_fields_textbox'] );
        }

        if(!empty( $_POST['custom_user_fields_select'] ))
        {
            $userData['select'] = sanitize_text_field( $_POST['custom_user_fields_select'] );
        }

        if(!empty( $_POST['custom_user_fields_checkbox'] ))
        {
            $userData['checkbox'] = intval( $_POST['custom_user_fields_checkbox'] );
        }

        if(!empty($userData))
        {
            update_user_meta( $user_id, 'custom_user_fields', $userData);
        }
    }

That's it, you can now create custom form fields and store them against the user meta to use in other places of your website.

The post Add Custom User Fields To User Profile Page appeared first on Paulund.

]]>
http://www.paulund.co.uk/add-custom-user-fields-profile-page/feed 0
Modify User Contact Fields In WordPress http://www.paulund.co.uk/modify-user-contact-fields http://www.paulund.co.uk/modify-user-contact-fields#comments Mon, 18 Aug 2014 16:43:24 +0000 http://www.paulund.co.uk/?p=10911 With WordPress each user has their own profile records, within these profile there are multiple feeds that can be populated by the user to give you more information about them allowing you customise the site a bit for just for them. One of the fields that you can easily customise is the User content information, by default WordPress comes with a number of contact fields such as: E-mail Website AIM

The post Modify User Contact Fields In WordPress appeared first on Paulund.

]]>
With WordPress each user has their own profile records, within these profile there are multiple feeds that can be populated by the user to give you more information about them allowing you customise the site a bit for just for them.

One of the fields that you can easily customise is the User content information, by default WordPress comes with a number of contact fields such as:

  • E-mail
  • Website
  • AIM
  • Yahoo IM
  • Jabber

These are all quite old and I can't remember the last time I've used them and certainly don't want the user to enter this information. We can update these contact fields with information that has a bit more up to date with communication methods.

The different content fields is an array of fields which has a filter user_contactmethods that you can hook into and change the values for. All you have to do is use this filter and change the values of the array. You can use the unset() function to remove contact fields you don't need and add new elements to the array for new contact fields.

function change_user_contact_information( $fields )
{
    unset($fields['aim']);
    unset($fields['yim']);
    unset($fields['jabber']);

    $fields['twitter'] = __('Twitter');
    $fields['facebook'] = __('Facebook URL');
    $fields['googleplus'] = __('Google+ URL');
    $fields['linkedin'] = __('Linkedin');
    $fields['skype'] = __('Skype');

    return $fields;
}
add_filter('user_contactmethods', 'change_user_contact_information');

To get this contact information back out you need to use the function get_the_author_meta().

<?php get_the_author_meta( $field, $userID ); ?>

This takes 2 parameters the field ID and the user ID, therefore if you want to get the new twitter value you need to pass in twitter as the $field parameter.

$twitterUsername = get_the_author_meta( 'twitter', $userId );
$facebookUsername = get_the_author_meta( 'facebook', $userId );
$googleplusUsername = get_the_author_meta( 'googleplus', $userId );
$linkedinUsername = get_the_author_meta( 'linkedin', $userId );
$skypeUsername = get_the_author_meta( 'skype', $userId );

The post Modify User Contact Fields In WordPress appeared first on Paulund.

]]>
http://www.paulund.co.uk/modify-user-contact-fields/feed 0
Add Scripts To Shortcode Only When Used http://www.paulund.co.uk/add-scripts-shortcode-used http://www.paulund.co.uk/add-scripts-shortcode-used#comments Thu, 14 Aug 2014 06:58:59 +0000 http://www.paulund.co.uk/?p=10915 Since version 2.5 WordPress introduced a new way of developers to provide dynamic content for the content author of the website with the use of Shortcodes. What Is A Shortcode? A shortcode allows the user to run a PHP function at any point you want in the content. A default shortcode you get with WordPress is the gallery shortcode, to add a gallery to your website all you have to

The post Add Scripts To Shortcode Only When Used appeared first on Paulund.

]]>
Since version 2.5 WordPress introduced a new way of developers to provide dynamic content for the content author of the website with the use of Shortcodes.

What Is A Shortcode?

A shortcode allows the user to run a PHP function at any point you want in the content. A default shortcode you get with WordPress is the gallery shortcode, to add a gallery to your website all you have to do is add [ gallery ] to the content area of your website.

The name inside the square brackets is the name of the shortcode that you want to run at this position of the content. WordPress will then search for shortcodes on the the_content filter and using the function do_shortcode() will run the functions at this point of the content, the return of these functions will then be output into the rest of the content area.

Shortcodes allows you to send extra parameters to the function by using attributes.

[shortcode_example attribute1="stuff" attribute2="things"/]

In the shortcode function the developer can now look up these attributes and use these values to change the output. You can also add content into the shortcode along with the attributes.

[shortcode_example attribute1="stuff" attribute2="things"]Shortcode Content Can Go Here[/shortcode_example]

This is great for the author as they now have full control of any functions that can help add dynamic controls to the site.

Styles And Scripts In Shortcodes

As shortcodes are used to add more dynamic content to the site it can be used to add Google maps or another third party to your application. If you want to add these third parties to your website then this would normally be done with Javascript.

When you use Javascript in your WordPress site you would normally have to use the action wp_enqueue_scripts.

add_action( 'wp_enqueue_scripts', 'add_javascript' );
function add_javascript()
{
    wp_enqueue_script(...);
}

Problem With Scripts And Shortcodes

The problem we get with shortcodes and queuing script files is that whenever we register the shortcode we need to register the Javascript at the same time. This means that WordPress will load the shortcode and the Javascript with the page even when the Shortcode isn't being used.

add_shortcode( 'google_map', 'add_google_map');
function add_google_map( $atts, $content )
{

}

add_action( 'wp_enqueue_scripts', 'add_javascript' );
function add_javascript()
{
    wp_enqueue_script(...);
}

Therefore if we have a Google Maps shortcode we will be including the Google Maps Javascript file on every page of our WordPress site even if the shortcode isn't being used. There is no need to include the Javascript on a page where the Google map isn't being displayed we are just adding more weight and slowing down the page.

So we need to find a way of only loading the Javascripts when the shortcode is being used, how can we solve this problem?

We could add the wp_enqueue_script() inside the shortcode function like this.

add_shortcode( 'google_map', 'add_google_map');
function add_google_map( $atts, $content )
{
    wp_enqueue_script(...);
}

But this won't work, it's too late, WordPress will not run be able to queue up the scripts.

The solution would be to add the Javascript in the footer of the application using wp_footer. Adding the script in the footer event allows us to set a global variable at the point of running the shortcode code, then in the wp_footer action we can do a check for this global variable and if it's set then we add the Javascript into the footer of the page.

add_shortcode( 'google_map', 'add_google_map');
function add_google_map( $atts, $content )
{

}

add_action( 'wp_footer', 'add_javascript' );
function add_javascript()
{
    wp_enqueue_script(...);
}

Shortcode OOP Class

The easiest way of doing this is by using a class to add the shortcode to the application. The following class will demo how you can make sure you only add Javascript when the shortcode is being used.

We start off by creating a class variable of $addScript and set this to false, this is the variable we are going to use to see if the shortcode is ran. Next we add a constructor to the class, the purpose of the constructor is to define the actions and register the shortcode.

The important thing to notice is in the shortcode function we start off by changing the value of the variable to true, so that in the footer action the shortcode function would of already ran, so we can check if this class variable is true. If the $addScript variable is still false, then we know the shortcode didn't run and we don't need to add the Javascript.

$shortcode = new Shortcode_Class();
class Shortcode_Class
{
    /**
     * If you should add the script or not
     *
     * @var bool
     */
    private $addScript = false;

    public function __construct()
    {
        add_shortcode('test_shortcode', array($this, 'shortcode_content'));

        // wp_enqueue_scripts
        // If you use the below the CSS and JS file will be added on everypage
        // add_action( 'wp_enqueue_scripts', array($this, 'add_shortcode_scripts'));

        // Add styles and scripts to the page
        add_action('wp_footer', array($this, 'add_shortcode_scripts'));
    }

    public function shortcode_content( $attr, $content )
    {
        $this->addScript = true;
        ?>
        <h1>Shortcode Content Being Displayed</h1>
        <?php
    }

    public function add_shortcode_scripts()
    {
        if(!$this->addScript)
        {
            return false;
        }

        wp_enqueue_script('shortcode-js', get_stylesheet_directory_uri() . '/js/shortcode.js', false);
    }
}

The post Add Scripts To Shortcode Only When Used appeared first on Paulund.

]]>
http://www.paulund.co.uk/add-scripts-shortcode-used/feed 0
Get A List Of Registered Actions In WordPress http://www.paulund.co.uk/get-list-registered-actions-wordpress http://www.paulund.co.uk/get-list-registered-actions-wordpress#comments Mon, 11 Aug 2014 19:05:30 +0000 http://www.paulund.co.uk/?p=10902 WordPress actions and filters is an event driven architecture that allow you to run specific code at certain times in your application. To do this WordPress uses two functions the add_action() to add new callback functions to an action, and the do_action() function which will run all the callback functions assigned to this action. In a recent project I was testing some code that used AJAX to run an action

The post Get A List Of Registered Actions In WordPress appeared first on Paulund.

]]>
WordPress actions and filters is an event driven architecture that allow you to run specific code at certain times in your application. To do this WordPress uses two functions the add_action() to add new callback functions to an action, and the do_action() function which will run all the callback functions assigned to this action.

In a recent project I was testing some code that used AJAX to run an action in a WordPress plugin. The problem I was having was that this action wasn't being called when it should of been, because this was using AJAX I needed a way of finding out if the code that add the action was actually being ran.

So I needed a way of finding out if the action I add was registered with WordPress so it understood what code to run on this action.

Whenever you want to add an action to WordPress you need to use the function add_action(), the code underneath this will add a new element to an array called $wp_filter.

Then if you look at the function that runs the actions do_action() function this will search for the action in the same $wp_filter variable. Which means all the registered actions will be added to this array, so if you want to view what actions have been registered at a certain time in your code you simply have to print out the elements in this array.

global $wp_filter;

echo '<pre>';
print_r($wp_filter);
echo '</pre>';

The post Get A List Of Registered Actions In WordPress appeared first on Paulund.

]]>
http://www.paulund.co.uk/get-list-registered-actions-wordpress/feed 0