• Regular Expression Example: Wrapping the Second through Last Words in a Span Element

    For the past week, I have been working on a website for an emergency medical services association. To fit the client’s wishes, the design called for the first word in titles to be blue followed by all other words being red.

    I do not know a way to do this with just HTML, so I decided that I would wrap the second through the last words in a span  element. Then I could add some LESS like this to achieve the color effect I wanted.

    [code lang=css]
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
    color: blue;

    span {
    color: red;
    }
    }
    [/code]

    But, how do I get the span element in the titles?

    Using Regular Expressions to Add the Span

    Regular expressions are a very powerful feature of many languages. They allow us to create very complex rules to match phrases in code, words, etc. We can also “capture” parts of these rules, which will prove useful in this example!

    Here is a PHP function with a regular expression example that takes a title and wraps the second through last words in a span  element.

    [code lang=php]
    function span_the_title( $title ) {
    return preg_replace( '#(S+)s(.+)#', '$1 <span>$2</span>', $title );
    }
    [/code]

    Let’s break this down. Notice that I am passing $title in to the function. This is the title that we will actually be filtering in the regular expression. Now take a look at the preg_replace() function. This function takes the following arguments:

    1. A regular expression that is the pattern to search for.
    2. A string to replace matched expressions with. Notice how I used $1 and $2 in the second argument above. This is because I am referencing part of the matched regular expression from the first argument. More on this later.
    3. The third argument is the title, in this case, or really any string.

    Let’s Break It Down

    (more…)

  • Animated GIF Not Working in WordPress?

    After recently trying to post an animated GIF in a WordPress post, I was disappointed after saving the post and seeing that the image wasn’t animating.

    Figuring that I did something wrong, I checked that the animated GIF worked on my computer and re-uploaded the image, but the animated GIF still did not work.

    The issue was that I was using a cropped version of the meme that I uploaded. I assume that in the process of resizing the meme that the frames in the animated GIF were also stripped. This made the animated GIF just a regular image. and it didn’t matter how many times I re-uploaded the animated GIF, as long as I used any other size than the original, the animated GIF would not work.

    How Do You Fix It?

    (more…)

  • Change Password on WordPress.org

    After creating a new WordPress.org account today, and receiving an auto-generated password, I was reminded of just how difficult it is to change passwords on WordPress.org.

    Googling for an answer made me realize just how many other people had this same issue. I saw some suggestions that stated to click a View your profile link. But the thing is that the layout of WordPress.org is not uniform, so this View your profile link doesn’t show everywhere.

    After some more looking, and a bit of searching, I found that the View your profile link can be found specifically on the WordPress.org Forums.

    WordPress Forums

    Notice that the View your profile is at the top right of this page. Or you can click this link which should take you directly to your profile.

    How to Change a Password on WordPress.org

    To change your password, simply follow these steps:

    (more…)

  • Get Categories for Custom Post Types and Taxonomies

    I recently built my own basic downloads manager plugin because I wanted something stupid simple. The bare functionality I needed was the title, a description, the file, and categories So, I created a custom post type and then added a few meta boxes with the Custom Metaboxes and Fields Class.

    I wrote all of the above in less than 10 minutes. The problem  I then encountered was figuring out how to get the list of categories that a download was assigned to.

    This is simple when just working with regular posts; Just use the get_categories() function. However, categories within custom post types are a different beast…

    Custom Post Types DO NOT Have Categories

    I spent hours trying to figure out how to get the categories from a custom post type. And you know what I figured out after all of that wasted time? That custom post types do not have categories…

    You see, categories are a type of taxonomy that is built-in to WordPress and used to categorize posts. When we create a “category” for a custom post type, we are actually creating a completely new taxonomy (even though we may in fact call it ‘categories’).

    Take this custom taxonomy example below:

    function cw_cpp_slideshow_categories() {
        $field_args = array(
            'labels' => array(
                'name' => 'Categories', 'taxonomy general name',
                'singular_name' => 'Category', 'taxonomy singular name',
                'search_items' => 'Search Categories',
                'all_items' => 'All Categories',
                'parent_item' => 'Parent Category',
                'parent_item_colon' => 'Parent Category:',
                'edit_item' => 'Edit Category',
                'update_item' => 'Update Category',
                'add_new_item' => 'Add New Category',
                'new_item_name' => 'New Category',
                'menu_name' => 'Categories',
            ),
            'hierarchical' => true
        );
        register_taxonomy( 'slideshow_categories', 'slideshow', $field_args );
    }
    add_action( 'init', 'cw_cpp_slideshow_categories', 0 );

    This is some code that I use to add categories to a slideshow custom post type. Look specifically at the line where I call register_taxonomy() . Notice how I define the taxonomy as slideshow_categories , then assign it to post type slideshow , then I pass in various arguments, such as labels, in the 3rd parameter.

    So, while I created a taxonomy that looks and functions almost exactly like categories does with posts… I actually created a new taxonomy named slideshow_categories .

    Confusing? Yea, a bit…

    Well, here’s a little bit more confusion. You know what you usually call categories? Those are actually named terms in other taxonomies…

     So, How Do I Get Categories for Custom Post Types?

    The answer is pretty simple just use get_terms(). The only parameter you need to pass in to get_terms()  is a taxonomy name, slideshow_categories from the example above.

    But, if you need to do some special ordering, excludes, etc… You can also pass an array of arguments as the second parameter. Check out the codex for get_terms().

    Questions or Comments?

    If this helped you or if you just find it funny how long it took me to figure this out… leave comment below!

  • Dynamic Google iFrames in WordPress

    In a recent client website, I needed to add Google iFrame maps with links to directions into a client’s contact page. To do this, I looked at the default iFrame code that Google maps generates and realized that to dynamically create a Google iFrame map that I would need both an address and coordinates.

    Because all that I had to work with was the client’s addresses, I knew I’d need to geocode the address before I could generate the iFrame.

    Geocoding with Google’s API

    Geocoding an address through Google’s API is a fairly straightforward process. To do it, you just need to query the API like this:

    [code lang=”php”]
    $address = urlencode( "{$listings[‘address_1’]} {$listings[‘city’]} {$listings[‘state’]} {$listings[‘zip’]}" );
    $response = json_decode( wp_remote_retrieve_body( wp_remote_get("http://maps.googleapis.com/maps/api/geocode/json?address={$address}&amp;sensor=false") ), true );
    [/code]

    Querying the API like above will you results like these:

    [code lang=”text”]
    Array
    (
    [results] => Array
    (
    [0] => Array
    (
    [address_components] => Array
    (
    [0] => Array
    (
    [long_name] => 3410
    [short_name] => 3410
    [types] => Array
    (
    [0] => street_number
    )

    )

    [1] => Array
    (
    [long_name] => Midwestern State University
    [short_name] => Midwestern State University
    [types] => Array
    (
    [0] => establishment
    )

    )

    [2] => Array
    (
    [long_name] => Taft Boulevard
    [short_name] => Taft Blvd
    [types] => Array
    (
    [0] => route
    )

    )

    [3] => Array
    (
    [long_name] => Wichita Falls
    [short_name] => Wichita Falls
    [types] => Array
    (
    [0] => locality
    [1] => political
    )

    )

    [4] => Array
    (
    [long_name] => Wichita County
    [short_name] => Wichita County
    [types] => Array
    (
    [0] => administrative_area_level_2
    [1] => political
    )

    )

    [5] => Array
    (
    [long_name] => Texas
    [short_name] => TX
    [types] => Array
    (
    [0] => administrative_area_level_1
    [1] => political
    )

    )

    [6] => Array
    (
    [long_name] => United States
    [short_name] => US
    [types] => Array
    (
    [0] => country
    [1] => political
    )

    )

    [7] => Array
    (
    [long_name] => 76308
    [short_name] => 76308
    [types] => Array
    (
    [0] => postal_code
    )

    )

    )

    [formatted_address] => 3410 Taft Boulevard, Midwestern State University, Wichita Falls, TX 76308, USA
    [geometry] => Array
    (
    [location] => Array
    (
    [lat] => 33.8764591
    [lng] => -98.5193496
    )

    [location_type] => ROOFTOP
    [viewport] => Array
    (
    [northeast] => Array
    (
    [lat] => 33.877808080291
    [lng] => -98.518000619708
    )

    [southwest] => Array
    (
    [lat] => 33.875110119708
    [lng] => -98.520698580292
    )

    )

    )

    [types] => Array
    (
    [0] => street_address
    )

    )

    )

    [status] => OK
    )
    [/code]

    First, notice that geocoding the above address returned a lot of information. Not only do we get the latitude and longitude back, but we also get the establishment listing, Midwestern State University in this case. From here it is a matter of pulling out the latitude and longitude we need and then putting these into the iFrame.

    Generating Dynamic Google iFrames

    Now that we have all of the information we need, we just need to plug it into the iFrames. Here is my completed example:

    [code lang=”php”]
    <?php

    $listings = array(
    array(
    ‘address’ => ‘3410 Taft Blvd’,
    ‘city’ => ‘Wichita Falls’,
    ‘state’ => ‘Tx’,
    ‘zip’ => 76308
    )
    )

    foreach ( $listing as $listing ) {
    $address = urlencode( &quot;{$listings[‘address_1’]} {$listings[‘city’]} {$listings[‘state’]} {$listings[‘zip’]}&quot; );
    $response = json_decode( wp_remote_retrieve_body( wp_remote_get(&quot;http://maps.googleapis.com/maps/api/geocode/json?address={$address}&sensor=false&quot;) ), true );
    $geometry = $response[‘results’][0][‘geometry’];

    // echo $geometry[‘location’][‘lat’] . ‘,’ . $geometry[‘location’][‘lng’];
    if( ‘OK’ == $response[‘status’] != ) {
    ?>
    [googlemaps https://www.google.com/maps/?f=q&source=s_q&hl=en&geocode=&q=&lt;?php echo $address; ?>&t=m&ll=<?php echo $geometry[‘location’][‘lat’];?>, <?php echo $geometry[‘location’][‘lng’];?>&z=18&iwloc=&output=embed&w=100&h=300]

    <a class=&quot;map&quot; title=&quot;Get Directions&quot; href=&quot;http://maps.google.com/maps?saddr=&daddr=&lt;?php echo $address; ?>&quot; target=&quot;_blank&quot;>
    <small>Click for Directions</small>
    </a>

    <?php
    }
    }
    [/code]

    Questions, Comments, Bugs?

    If you have any questions or comments, please leave a comment below. If you notice a bug or feel that you could make this better, please leave a comment here and/or on the public gist at https://gist.github.com/ebinnion/7ff42563ca63bb9bb6df

  • Auto Versioning CSS and Javascript in WordPress

    As a developer, I am very well acquainted with cache issues when developing JavaScript and/or CSS. From experience, I have learned to use LiveReload to automatically reload my web site while working locally and to do a hard refresh in the browser after pushing files to the server.

    But, many clients I have worked with aren’t aware that they may not be looking at the latest version of their site. So, when they check their site and see that the change I said I made isn’t there, they tend to be mad.

    Now, there is a way to automatically bust the cache and force the client’s browser to pull down the latest file Simply add a GET parameter at the end of your CSS or JavaScript.

    [code lang=text]
    http://yoursite.com/style.css?ver=1
    [/code]

    Notice how the above example has a version number at the end of the URL. The browser sees each version number as a different URL, so when you increment the version number, this triggers the browser to download the latest version of the JavaScript or CSS. While this is a great method, what if there was a way to automatically increment the version number instead of it being reliant upon a developer to remember to increment it?

    Auto Versioning CSS and JavaScript in WordPress

    After looking into this myself, I found a good tutorial about auto-versioning CSS in WordPress. This technique makes use of the PHP filemtime() to get the timestamp that the CSS was last updated. Thus, every time CSS or JavaScript changes, we can use the timestamp that file was changed (this is a unique integer) to automatically version our CSS and JavaScript.

    While the method above does seem to work, it requires some unnecessary htaccess rewrites since the developer is actually changing the filename, as opposed to adding a GET parameter at the end of the filename.

    To remedy this, and remove the need for all htaccess rewrites, let’s just move the timestamp to the end of the CSS or JavaScript filename. Here’s how you would enqueue auto versioned CSS and JavaScript  in WordPress with this auto versioning.

    [code lang=text]
    <?php
    /**
    * Auto-versioning CSS and JavaScript in WordPress
    * @author Eric Binnion
    * https://eric.blog
    */

    add_action("wp_enqueue_scripts", "auto_version_scripts", 20);
    function auto_version_scripts() {
    // Get last modified timestamp of CSS file in /css/style.css
    $ctime = filemtime( template_directory() . '/css/style.css' );

    // Get last modified timestamp of JS file in /js/main.js
    $jtime = filemtime( template_directory() . '/js/main.js' );

    wp_enqueue_style(
    'custom_style', // handle for style.css
    get_template_directory_uri() .'/css/style.css' ,
    array(), // dependencies
    $ctime, // version number
    true // load in footer
    );

    wp_enqueue_script(
    'custom_js', // handle for main.js
    get_template_directory_uri() .'/js/main.js' ,
    array(), // dependencies
    $time, // version number
    true // load in footer
    );
    }
    [/code]

     Questions, Comments, Bugs?

    If you have any questions or input, please leave a comment below. If you notice any potential bugs, please leave a comment below or leave a comment at the public gist for this function at https://gist.github.com/ebinnion/c04265e34151a5e9a14e.

  • Remove Files from Git After Adding/Updating .Gitignore

    I recently inherited a project from a beginning developer. After inheriting the project I realized that, while the developer was using Git to source control the project, the developer had completely forgot to add a .gitignore.

    This meant that I now needed to add a .gitignore file as well as remove files from git that were tracked that shouldn’t have been tracked.

    This isn’t usually a big deal when ignoring a single file or two The command to remove a single file is:

    git rm --cached <file>
    

    But, since we use Grunt and Sass for our web development projects, there were a ton of files within node_modules  and .sass_cache  as well as .DS_Store files throughout.

    To get around writing multiple commands to ignore all of these files and un-track them, I did this:

    git rm -r --cached .
    git add -A
    git commit -am 'Removing ignored files'
    

    The first command will un-track all files in your git repository.

    The second command will then add all of the files in your git repository, except those that match rules in your .gitignore. Thus, we have un-tracked several files with just two commands.

    Then the last command is to commit the changes, which will just be removed files.

  • Using MaxCDN with WP Engine

    I love WP Engine’s service. Seriously. And while I’ve always had great performance and support at WP Engine, I knew that I could improve the performance of my website a bit by using a CDN.

    The thing is that I didn’t want to pay the extra $19.95 for WP Engine’s CDN because I already had access to a MaxCDN account.

    While setting up MaxCDN with other hosts is fairly straightforward, thanks to the W3TC plugin, this is not the case with WP Engine since W3TC is on the disallowed plugins list.

    But, looking into different options, I realized that I could manually set up CDN integration between my WP Engine site and MaxCDN using a pull zone and a bit of RegEx.

    What is a Pull Zone?

    A pull zone is a method which MaxCDN uses to pull static assets from a site and store them on MaxCDN servers.

    With a pull CDN, the site owner leaves the content on their server and and rewrites their URLs to point to the CDN. When asked for a specific file, the CDN will first go to the the original server, pull the file and serve it. The CDN will then cache that file until it expires

    [ref]Sourced from Who is Hosting This?[/ref]

    .

    For example, anytime someone goes to http://cdn.domain.com/some-image.jpg, this tells MaxCDN to pull the image from http://domain.com/some-image.jpg , cache it, and then serve the cached version from now on.

    This is much simpler than an origin push zone because the CDN is doing all of the hard work.

    Set Up MaxCDN Pull Zone

    Setting up a pull zone is a fairly simple process, and as such, I’ll simply forward you to MaxCDN’s documentation.

    Also, here is a video that will walk you through how to create a pull zone and then create the CNAME to use in your source code.

    Connect WP Engine to MaxCDN with RegEx

    The only thing missing at this point is changing our URLs to point to the CDN. This part can be a bit confusing because it requires using RegEx, but don’t fret too much I’ve done most of the work!

    To do this, navigate to the WP Engine tab of your WordPress admin http://yoursite.com/wp-admin/admin.php?page=wpengine-common, then add this snippet below into the HTML Post-Processing box in the Advanced Configuration.

    [code lang=”text”]
    #http://yoursite.com/(S*.(?:jpe?g|png|gif|ttf|otf|svg|woff|js|css))# =&gt; http://cdn.yoursite.com/$1
    [/code]

    This snippet will set up your site to serve all images, fonts, JavaScript, and CSS from your CDN.

    Before hitting save, be sure to change yoursite.com to your actual site URL. Also, this snippet assumes that you’re using a subdomain of cdn. If you are not, you will need to update this on the right hand side of the snippet.

    Questions or Comments

    If I didn’t explain something well enough, if I missed something, or if you just want to say “Thanks”, ?please leave a comment below.

  • WordCamp Austin 2014

    I recently had the pleasure of speaking at WordCamp Austin 2014 with the topic “Improving Development Workflow with Grunt JS.”

    This was a great experience as I was able to meet many influential WordPress community members that I have looked up to over the past several years including Chris Lema, Shawn Hesketh, Jason Cohen, and more. I was also very excited to finally meet Shayda Torabi and the new WP Engine community manager, Odas Williams, in person.

    All in all the event went well. Below are links to resources I talked about at #wcatx as well as some photos.

    This is the Gruntfile that we are currently using. Keep in mind that this is always being tweaked. https://gist.github.com/ebinnion/10926420

    Here is a link to my slides on SpeakerDeck. This includes the hidden slides which I decided not to talk about. https://speakerdeck.com/ebinnion/improving-wordpress-development-workflow-with-grunt

    Here is a link to my .bash_profile that I demoed during my talk. https://gist.github.com/ebinnion/11278400

  • A Great Day at the Fort Worth Children's Museum

    This past weekend we went to the Fort Worth Children’s Museum for a birthday celebration. While I initially gawked at the price to get into the museum, I was surprised by how much fun Hero and I both had.

    There were so many exhibits that including everything from dinosaurs to neon colored rocks while under black light.

    But, our most favorite attraction by far was this spinning ride.

  • Adding Featured Image in Genesis

    I recently switched my site over to Genesis and the Sixteen Nine theme. While I am super impressed with the framework and the child theme, I was disappointed to see that featured images are not included on individual posts.

    Because Genesis has such a great community, after a quick search I found an article which described how to add the featured images to individual posts.

    Here is that snippet:

    [code lang=text]
    add_action( 'genesis_after_post_title', 'child_featured_post_image' );
    function child_featured_post_image() {
    if ( $image = genesis_get_image( 'format=url&size=post-image' ) ) {
    printf( '<a href="%s" rel="bookmark"><img src="%s" alt="%s" /></a>', get_permalink(), $image, the_title_attribute( 'echo=0' ) );
    }
    }
    [/code]

    But, Natalie’s snippet didn’t work for me…

    Featured Image in Genesis HTML5

    After a little bit of digging, I found that her code had been written for Genesis 1.x. This was also brought up in the comments, which, in hindsight, I probably should have read before even trying to use the snippet 🙂

    Looking at the Genesis Hook Reference, I found the correct hook to use. I then recoded Valerie’s snippet to retrieve the featured image using the_post_thumbnail() , which is a core WordPress function. This is due more to my inexperience with Genesis than anything else. I can’t speak to which method is better.

    add_action( 'genesis_before_entry_content', 'child_featured_post_image' );
    function child_featured_post_image() {
    if( is_single() )
    the_post_thumbnail('post-image', array('class'=&gt;'aligncenter'));
    }

    This snippet will add a featured image to each post, if it exists, and apply a class of aligncenter  to it. You can change the alignment to be left or right aligned simply by changing aligncenter to alignleft or alignright .

  • Chinese Lantern Festival 2013

    For Sara’s 25th birthday, I took our family the Chinese Lantern Festival at Fair Park in Dallas.

  • Mobile WordPress Navigation with a Select

    Navigation is difficult enough in desktop view, but how does one deal with a potentially large navigation across multiple devices?

    It seems like the standard way to deal with mobile navigation is to set the navigation to display:none; and then toggle it with a hamburger icon. And while this is a fairly straight forward method, I’ve become fond of using a select statement and a bit of JavaScript to handle mobile navigation.

    But, the problem here is that WordPress’ default markup for menus uses an un-ordered list.

    Generating the Select from a WordPress Menu

    Luckily, given the location id for a menu, we can retrieve a set of menu items and then coax that into any output we would like.

    Below is an example of how to do this, modified from an example in the WordPress Codex.

    “`<?php
    $locations = get_nav_menu_locations();

    $menu = wp_get_nav_menu_object( $locations[ 'menu-location' ] );
    $items = wp_get_nav_menu_items($menu->term_id);

    echo '<select class="fancyDropdown">';
    echo '<option value="">Menu</option>';
    foreach($items as $key => $item) {
    echo '<option value="'.$item->url.'">'.$item->title.'</option>';
    }
    echo '</select>';

    [code lang=text]
    <br />Note that we are placing the links within the value for each option. Where we would use <code><a href="http://superhero.io"></a></code&gt;, we are now using <code><option value="http://superhero.io"></option></code&gt;.

    Also take note of the dummy option called 'Menu'. Since this option is first in the list, it will be shown by default and the 'Menu' text will act as a visual cue for a non-standard UI.

    <h3>And a Touch of Javascript</h3>

    Now that we have the select built, we need a way to navigate when the select has been clicked. For that, we'll use a little bit of javascript and jQuery.

    “`jQuery(document).ready(function($){
    $('.fancyDropdown').change(function(){
    var url = $(this).val();
    if ( url.length ) {
    window.location.href = url;
    }
    });
    });
    [/code]

    This little bit of javascript will get the URL from the selected option (stored as a value) and then navigate the current page to that URL. There is a simple check to see that the URL has length (is not null) which will prevent performing a redirect when the dummy ‘Menu’ option is selected.

    Bottom Line

    While using selects for your mobile users is a fairly straightforward and simple process… it does have its fallbacks.

    1. It requires javascript
    2. Is not a standard interaction on a website.

    While being a javascript solution is likely not a big issue, since slide out menus use javascript as well, you don’t want to risk confusing your visitors too much.

    That being said, I think this is a solid option to be considered in working with mobile navigation. What do you think?

  • Bootstrap Pager for WordPress

    In the process of building Scarlett, a Bootstrap WordPress theme for small businesses and freelancers, I frequently ran into issues where I needed to modify default WordPress output to fit it into Bootstrap’s styles. One such instance was when I wanted to paginate the blog index of the Scarlett theme.

    Normally, you would use get_next_posts_link(); and get_previous_posts_link(); to get a simple pager. But, these functions either return a link or an empty string.

    So, to coax that default output into something that would work with Bootstrap’s styles I ended up with this:

    “`<ul class=”pager”>
    <?php
    $next = get_next_posts_link( 'Newer →');
    $prev = get_previous_posts_link( 'Older ←' );

    if ( !empty($prev) ) {
    echo '<li class="previous">'.$prev.'</li>';
    }

    if ( !empty($next) ) {
    echo '<li class="next">'.$next.'</li>';
    }
    ?>
    </ul>

    [code lang=text]
    <br /><br /><br /><h3>Factoring Pager Snippet into a Function</h3>

    As I only needed to add a Bootstrap pager on the index page, I simply used this snippet directly in the <code>index.php</code>. But, if you were to add a pager in multiple parts of your theme, I would suggest breaking this functionality out into a function that goes into <code>functions.php</code>. Here is an example of what that might look like.

    “`<?php
    function bootstrap_wp_pager() {
    echo '<ul class="pager">';

    $next = get_next_posts_link( 'Newer →');
    $prev = get_previous_posts_link( 'Older ←' );

    if ( !empty($prev) )
    echo '<li class="previous">'.$prev.'</li>';

    if ( !empty($next) )
    echo '<li class="next">'.$next.'</li>';

    echo '</ul>';
    }
    [/code]

    This snippet would need to go in your functions.php. Then anytime you needed to add a pager, you would simply use <?php bootstrap_wp_pager(); ?> in your code.

  • Christmas in the Park 2013

    These pictures were taken at Six Flags over Texas in December of 2013.

  • Remove .sass-cache and node_modules from Sublime Text

    I’ve recently been playing with Foundation, Sass, and Grunt. And while each of these are powerful tools in their own right, they are quick to clutter up a project.

    Grunt creates a node_modules directory while Sass creates a .sass-cache directory.

    But don’t worry, because lucky users of Sublime Text have a simple fix.

    Add .sass-cache and node_modules to Folder Excludes List

    To exclude a directory from showing up in Sublime’s search and in the sidebar, all you need to do is add it to the folder_exclude_patterns key in your user preferences.

    To do this:

    • Click Sublime Text ? Preferences ? Settings – User
    • Add the snippet below
    {
    "folder_exclude_patterns": [".svn", ".git", ".hg", "CVS", ".sass-cache", "node_modules"],
    }
    

    This line of code should ignore the .sass-cache and node_modules directories as well as common source control directories.

  • How to Add a WordPress AJAX Nonce

    Using AJAX on your WordPress website can greatly enhance the user experience on your website. But, like all things web, you should properly secure your AJAX functions.

    One of the easiest ways to begin to secure your AJAX functions is to use a WordPress AJAX nonce, which is just a way to verify that all AJAX calls are originating from your website.

    What is a Nonce?

    WordPress describes nonces as “a one-time token generated by a website… This could prevent unwanted, repeated, expired, or malicious requests from being processed.”

    In other words, a nonce is a unique key that your website creates that allows you to verify actions. For the purposes of this article, we’re going to focus on using nonces to ensure that requests are originating from our own website.

    How to Implement a WordPress AJAX Nonce

    Implementing a nonce for your AJAX functions in WordPress is actually fairly straightforward. First, let’s start by generating the nonce. The proper way of doing this is by localizing your javascript files.

    [code lang=”php”]
    $params = array(
    ‘ajaxurl’ => admin_url(‘admin-ajax.php’, $protocol),
    ‘ajax_nonce’ => wp_create_nonce(‘any_value_here’),
    );
    wp_localize_script( ‘my_blog_script’, ‘ajax_object’, $params );
    [/code]

    This code will create an object containing values for:

    1. ajaxurl – This is the absolute address, taking into account http:// or https://, to your ajax processing script. This script is in the wp-admin folder, but can be used for front end ajax scripts as well.
    2. ajax_nonce – This is our nonce that we check in our ajax function. Notice how I used the string ‘any_value_here’ within the wp_create_nonce function… You can use any string, but be sure to remember what you use, because we will need to use the same string when we check the AJAX nonce.

    We can access the values in this object like this: ajax_object.ajax_nonce.

    Now that we have the AJAX nonce and URL setup, it’s time to go ahead and setup our AJAX call in our javascript file. Although I will be using the $.ajax function in this example, you can also use the $.post function. Here is an example of how to setup your AJAX call.

    [code lang=”javascript”]
    $.ajax({
    type : "post",
    dataType : "json",
    url : ajax_object.ajaxurl,
    data : ‘action=get_posts_commented&amp;email=’+user_email+’&amp;security=’+ajax_object.ajax_nonce,
    success: function(response) {
    // You can put any code here to run if the response is successful.

    // This will allow you to see the response
    console.log(response);
    }
    });
    [/code]

    Notice how we are adding the ajax_nonce to the end of our parameter string. We can then access this in the AJAX processing script using $_POST[‘security’].

    Alright, now that we’ve got our WordPress AJAX call setup, it’s time to go ahead and setup the PHP function that will process our AJAX call. Here is an example:

    [code lang=”php”]
    add_action(‘wp_ajax_get_posts_commented’, ‘get_posts_commented’);
    add_action(‘wp_ajax_nopriv_get_posts_commented’, ‘get_posts_commented’);
    function get_posts_commented(){
    check_ajax_referer( ‘any_value_here’, ‘security’ );

    $email = urldecode($_POST[’email’]);

    global $wpdb;
    $results = $wpdb->get_results($wpdb->prepare("
    SELECT
    comment_post_ID
    FROM
    {$wpdb->comments}
    WHERE
    comment_type = ” AND comment_approved = 1 AND comment_author_email = ‘%s’";,
    $email), ARRAY_A);

    echo json_encode($results);

    exit;
    }
    [/code]

    Notice that at the top of this WordPress AJAX function there this line:

    [code lang=”php”]
    check_ajax_referer( ‘any_value_here’, ‘security’ );
    [/code]

    This function is how we check the WordPress AJAX nonce. The first parameter is the key we assigned when creating the ajax_nonce above. In this example that is ‘any_value_here’. The second parameter lets the function know what parameter of the request to look in for the AJAX nonce.

    If the nonce is not set or incorrect, then check_ajax_referrer() will cause the AJAX call to die, protecting your AJAX call from invalid requests.

    Conclusion

    Checking for WordPress AJAX nonces is not a foolproof security solution for your AJAX calls, but it is definitely a good step in the right direction. If you’re making database calls in your AJAX function I would suggest you look at using $wpdb->prepare to sanitize variables used in your SQL statements.

  • I’ve got my kid on those learning games.

    I've got my kid on those learning games.

    I’ve got my kid on those learning games.

  • @drpeppergaming for the win!

    @drpeppergaming for the win!

    @drpeppergaming for the win!

  • Luxe marker at PSP Dallas

    Luxe marker at PSP Dallas

    Luxe marker at PSP Dallas