Author Archives: Ben Pearson

Highlights from WordCamp Melbourne 2013

A few of my favourite presentations from WordCamp Melbourne 2013.

Looking forward to reviewing the videos and slides when they become available. Many thanks to all involved for a great weekend.

Notes on the lesson Using the Query String of the the Tuts+ Course PHP Fundamentals by Jeffery Way.

These are my reference notes on the lesson Using the Query String of the the Tuts+ Course PHP Fundamentals by Jeffery Way.

Links

Notes

The query string is everything that comes after the question mark in the URL eg. http://benpearson.com.au/index.php?name=jeffery&job=developer

The query string contains key value pairs eg. name=jeffery and job=developer. They are seperated with and ampersand.

$_GET is a super global.

The following PHP will display the associative array of the $_GET super global.

var_dump($_GET);

 

The $_GET request (also known as a HTTP verb) is only used when you are fetching and displaying data.  It is not used to send data to update a database. You would use $_POST for that.

You need to test that an item exists in the super global before echoing it otherwise PHP will display an error on the page. Here’s an example of how this is done:

if ( isset( $_GET['job'] ) ) {
    echo $_GET['job'];
}

 

Assume all data received from the query string is dangerous as the URL can be edited by the user.

Run everything you echo from the query string through htmlspecialchars() first. This will convert all your special characters into their html entitys eg. < is converted to &lt;

Setting up Mixture to work with WordPress and Compass

Assuming you have Mixture and XAMPP (or similar local server) installed and your WordPress site is already working locally.

  • Make sure there’s no existing compass folder or config.rb file in your theme folder.
  • Start XAMPP (or other local server).
  • Start Mixture.
  • Click Open in Mixture and select your theme folder inside wp-content/themes
  • Select your theme folder for the Preprocessor location.
  • Enter your localhost URL for the Partner server address, in my case it’s http://localhost

Mixture will now report errors. Here’s how to fix them.

Assuming you have the following file structure in your theme folder:

WordPress theme file structure example

  • style.css in the root of the theme that only contains theme information header, an @import statement for your “global” css file (that contains all your styles) and maybe also an @import statement for your parent theme’s stylesheet if you are working on a child theme. Here’s an example style.css for a child theme:
/*
Theme Name:     Twenty Twelve Child
Description:    Child theme for the Twenty Twelve theme 
Author:         Ben Pearson
Author URI:     http://benpearson.com.au
Template:       twentytwelve
Version:        1.0
*/

@import url("../twentytwelve/style.css");

@import url("css/global.css");
  • All your SCSS files are kept in the an scss folder. I have a global.scss file in this folder that imports all the partials like _navigation.scss. This global.scss will be compiled to css/global.css and then imported by style.css
  • All your CSS will the exception of style.css is kept/compiled in a css folder.
  • All your images are kept in an images folder
  • All your javascript is kept in an js folder

Open the mixture.json file that has been newly created in your theme’s root folder and make the following change:

"useCompass": true,

This will create a compass folder in your theme folder with a config.rb file inside it.

Now change the preprocessorLocations in mixture.json to the root like so:

"preprocessorLocations": "/",

Open compass/config.rb and change the CSS, SCSS, images and javascript paths to the following:

css_dir = "css"
sass_dir = "scss"
images_dir = "images"
javascripts_dir = "js"

Click View locally in Mixture to view your site through Mixture and take advantage of it’s SASS/Compass compiler and live reload functionality.

 

Using Mixture with a virtual host (optional)

The following instructions work on Windows 7. They may also work on other operating systems.

Assuming you have already setup a virtual host.

Make the following changes to mixture.json, substituting bp.benpearson for the name of your virtual host.

"serverHostname": "bp.benpearson",
"serverPort": 80,
"simpleModePartnerServer": "http://bp.benpearson/",

When you click View locally in Mixture it will open the site at a URL like:

http://bp.benpearson:63229/

The :63229 is there because that’s the port that Mixture is using. To get rid of this you need to make sure port 80 is free for Mixture to use. In my case port 80 is being used by XAMPP.

 

References

Install XAMPP on Windows 7 and set up a virtual host

Installing XAMPP

Download XAMPP Installer for WIndows and install with default settings.

If you get a warning in XAMPP saying Skype is using port 80, do the following:

  • Stop all services and quit XAMPP
  • Open Skype
  • Tools -> Options -> Advanced settings -> Connection
  • Uncheck “Use port 80 and 443 as alternatives”
  • Run XAMPP as administrator

Setting up virtual hosts

  • Stop all services in XAMPP
  • Open Apache vhosts file located at: C:\xampp\apache\conf\extra\httpd-vhosts.­conf
  • First add a default virtual host buy adding the following code to the end of the file
<VirtualHost *:80>
    DocumentRoot "C:/xampp/htdocs"
    ServerName localhost
</VirtualHost>

This will stop the URL http://localhost/ from redirecting to the first real virtual host we create. This is handy when you need to access a URL like http://localhost/newsite/wp/wp-admin to install WordPress etc.

  • Next follow the examples in the vhosts file and add this code to the end of the file after our default virtual host.
<VirtualHost *:80>
    ServerAdmin postmaster@bp.benpearson
    DocumentRoot "C:/xampp/htdocs/benpearson"
    ServerName bp.benpearson
    ServerAlias www.bp.benpearson
    ErrorLog "logs/bp.benpearson-error.log"
    CustomLog "logs/bp.benpearson-access.log" combined
</VirtualHost>

This code will create a virtual host for bp.benpearson

  • Create the folder C:/xampp/htdocs/benpearson and put a test index.html in there.
  • Run notepad as an administrator
  • Open the Windows hosts file located at: C:\Windows\System32\drivers\etc\hosts (may need to select “All Files” to see the hosts file in the etc directory)
  • Add the following line to the bottom of the file (the space after the IP address should be a tab) :
127.0.0.1	bp.benpearson
  • Start XAMPP Apache service.
  • Go to bp.benpearson in a browser and you should see your test index.html.

Reference: How to set up XAMPP with virtual hosts (some instructions conflict with the above)

Create a unstyled linked list of all tags used in a WordPress blog

Need a tag cloud without all the styles? Just a simple unstyled, linked list of all the tags used throughout a blog?

Try the wp_list_categories() function. Weird, I know. The taxonomy parameter of the function enables it to list post tags instead of categories.

The following displays a linked list of all the post tags sorted by popularity.

<ul>
    <?php wp_list_categories( array( 'taxonomy' => 'post_tag',
                                     'orderby' => 'count',
                                     'order' => 'DESC',
                                     'title_li' => '' ) ); ?>
</ul>

The empty title_li parameter is necessary to remove the default “Categories” title and it’s outer ul wrap.

Reference: wp list categories() is the WordPress Codex.

Using rem units

What are they?

rem is a CSS3 unit which can be used instead of the em and px units. rem stands for “root em”.

Why use the rem unit?

Like the em unit, the rem unit is useful in responsive design. But whereas the em unit is relative to the font-size of it’s parent, the rem unit is relative to the root or html element.

That means that we can define a single font size on the html element and define all rem units to be a fraction/multiple of that and not have to worry about units compounding as they do with the em unit.

Here is a basic example of rem usage.

html { font-size: 62.5%; } 
body { font-size: 1.4rem; } /* = 14px */
h1   { font-size: 2.4rem; } /* = 24px */

A base font-size of 62.5% is used so we have the convenience of sizing the rem units in a way that is similar to using px.

font-size: 100% is equal to font-size: 16px in most browsers. 62.5% of 16px is 10px. So 1rem would equal 10px and 2rem would equal 20px etc.

Browser support

The rem unit is not supported by IE8 and below. To overcome this, a pixel unit fall-back needs to be declared. SCSS mixins can make this a little easier.

html {
    font-size: 62.5%; /* = 10px; */
}

/* Declare the mixin with a default value of 16 for it's $pixels argument */
@mixin font-size( $pixels: 16 ) { 

    /* Convert the $pixels value to px units using the + operator */  
    font-size: $pixels + px; 

    /* Convert the $pixels value to rem units.  */
    font-size: (pixels / 10) + rem; 

}

The following is an example of how to use the mixin if you want a want a font-size of 20px and 2rem.

p {
    @include font-size(20);
}

 

References:

Replace a non pluggable function in a WordPress parent theme with a customized function in the child theme

A pluggable function is a a function wrapped in a function_exists() call eg.

<?php 
if ( ! function_exists( 'my_pluggable_function' ) ) {
    function my_pluggable_function() {
        /* Some code goes here */
    }
}
?>

When using a child theme, you can override pluggable functions by defining them first in your child theme’s functions.php file. The child theme’s functions.php file is included before the parent theme’s file, so the child theme functions would be used.

If the functions that are not pluggable are instead attached to a filter or action hook you can replace them using the following method in the child theme’s functions.php. I have used the example of the widgets_init action.

  1. Unhook the parent theme’s widget function (declared in the parent theme’s functions.php) from the widgets_init action
  2. Create a customized function to register widget areas for the child theme
  3. Hook our new function to the widgets_init action

Again, this code would go in the child theme’s functions.php with no need to modify the parent theme’s functions.php.

<?php 
remove_action( 'widgets_init', 'parenttheme_widgets_init' );

function childtheme_widgets_init() {
    /* Some code to register widget areas goes here */
}

add_action( 'widgets_init', 'childtheme_widgets_init' );
?>

Basic HTML5 “Coming soon” and “Scheduled maintenance” page templates

Text only page templates for website status messages.

Coming soon

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Website coming soon</title>
    <style type="text/css">
        h1 { text-align: center; }
    </style>
</head>
<body>
    <h1>Coming soon</h1>
</body>
</html>

View demo on CodePen

 

Scheduled maintenance

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Scheduled maintenance</title>
    <style type="text/css">
        h1 { text-align: center; }
    </style>
</head>
<body>
    <h1>Site temporarily unavailable due to scheduled maintenance</h1>
</body>
</html>

View demo on CodePen

wp_enqueue_script() – the recommended method of adding JavaScript to WordPress

This function includes the script if it hasn’t already been included, and safely handles dependencies (scripts that must be loaded before the script).

<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );?>

$handle is the name of the script in lowercase.

$src (optional) URL to the script. This parameter is only required when WordPress does not already know about this script. You should never hardcode URLs to local scripts, use get_template_directory_uri() (for Themes) and plugins_url() (for Plugins).

$deps (optional) array of handles (lowercase names) of any script that this script depends on. This parameter is only required when WordPress does not already know about this script.

$ver (optional) string specifying the script version number. This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available.

$in_footer (optional) boolean of whether or not the script should be loaded at the bottom of the <body>. Default is false.

 

This following code will load the version of jQuery that comes with WordPress on both the front end and the admin side. It will only load if jQuery it has not yet been included. This code needs to be placed before wp_head().

<?php wp_enqueue_script('jquery'); ?>

 

The example below

  • only loads the fancybox script on the front end, via use of the wp_enqueue_scripts action hook
  • uses get_stylesheet_directory_uri() for the path to the fancybox script
  • loads the script’s dependency jquery before loading the fancybox script
  • loads version 1.2.6 of the fancybox script
<?php
function my_scripts_method() {
    wp_enqueue_script('jquery');
    wp_enqueue_script(
        'jquery.fancybox',
        get_stylesheet_directory_uri() . '/js/jquery.fancybox.js',
        array('jquery'),
        '1.2.6'
    );
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
?>

 

wp_enqueue_scripts() in the WordPress Codex