CMSs and WordPress Lessons and Materials for WIE Course

Chapter 8: Advanced WordPress Customization

Table of Contents

Custom Posts and Pages

We know that WordPress has two ways to display content: Pages and Posts. As a reminder, pages are more permanent and posts and meant to be time-based.

We also know that the page.php file is for displaying pages and the single.php file is for displaying posts. Well, what if we want to make new types of posts (for organization reasons or as new types of content that are outside of the scope of a “blog post.”)? What if we want to have different ways to display page content?

This is where custom posts and pages come into play. There are plenty of scenarios where you may need to go away from the typical look of your page or post. Adding custom page or post templates allows you to add multiple looks for different types of posts or pages. The concept behind their customization is very different and will be useful for entirely different reasons.

Custom Posts

A Custom Post will be a completely new content type in the WordPress CMS. The usefulness of this functionality cannot be understated, but it is complicated and can be confusing.

WordPress Codex - Custom Post Types

Smashing Magazine - The Complete Guide To Custom Post Types

Can you think of some uses for a custom post type?

Tutorial: Adding Custom Post Type

We are going to use the Smashing Magazine - The Complete Guide To Custom Post Types guide for this tutorial. I am going to do it a bit different, but if I confuse you with my method feel free to reference it.

Before we get too deep into the tutorial let’s come up with a concept so that we can focus our understanding on a real world example. Our concept will be “Interesting Web Resources.” This will allow us to create links to interesting posts and brief descriptions of them. We could apply this as a method for linking to outside sources without clogging up our own content.

Since there is a lot of complicated PHP work in this tutorial, I am going to add the various parts much slower and talk about what is happening in more detail.

Step 1: Add the Register Function

functions.php

function custom_web_resources() {

}
add_action( 'init', 'custom_web_resources' );

You should recognize this code from the widget initialization code; The same concepts that are there apply here. You are creating a function and adding that function to WordPress through the add_action function.

Step 2: Add the Custom WordPress Function

Next we will add a WordPress function used for adding custom post types. It is called register_post_type and more information about it can be found here: WordPress Codex - Function Reference - Register Post Type

This codex entry can help you go through the next step of our tutorial if you are having trouble.

functions.php

function custom_web_resources() {
  $labels = array();
  $args   = array();
  register_post_type( 'resources', $args ); 
}
add_action( 'init', 'custom_web_resources' );

As you can see, we used the register_post_type function to register a post type called ‘resources,’ included an empty array called $args, and included an empty array called $labels. The $args array is called where the function’s arguments would go.

This is done a bit different than the Smashing Magazine tutorial but I think it is a slightly better way to go about it.

Step 3: Add our Options into the Arrays

There are numerous options that can be added to the register_post_type function. Instead of passing these options through directly, we are creating an object as an array to hold them. This will make our code a bit more organized and modular (which is a very good thing).

functions.php

<?php

function custom_web_resources() {

  $labels = array(
    /*--- Begin Labels Options ---*/
    'name'               => _x( 'Links', 'post type general name' ),
    'singular_name'      => _x( 'Link', 'post type singular name' ),
    'add_new'            => _x( 'Add New', weblink ),
    'add_new_item'       => __( 'Add Link' ),
    'edit_item'          => __( 'Edit Links' ),
    'new_item'           => __( 'New Link' ),
    'all_items'          => __( 'All Links' ),
    'view_item'          => __( 'View Links' ),
    'search_items'       => __( 'Search Links' ),
    'not_found'          => __( 'No links found' ),
    'not_found_in_trash' => __( 'No links found in the Trash' ), 
    'parent_item_colon'  => '',
    'menu_name'          => 'Web Links'
  );

  $args = array(
    /*--- Begin Arguments Options ---*/ 
    'labels'        => $labels,
    'description'   => 'Place to put useful links to other web resources',
    'public'        => true,
    'menu_position' => 5,
    'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt', 'comments' ),
    'has_archive'   => true,
  );

  register_post_type( 'resources', $args ); 
}

add_action( 'init', 'custom_web_resources' );
?>

One thing to notice is that the entire $labels array is brought in as an option to the $args array. Consider what each item in the options does so that you can see the sort of things that WordPress would want in order to make sure the CMS is using this new custom post type as effectively as possible.

Also, consider the ‘_x’ and the [‘’ functions](http://wpengineer.com/2237/whats-the-difference-between--_e-_x-and-_ex/) in the $args array. What do they do? How is this useful?

There are even more parameters that can be passed to the arguments. These can be found in the WordPress Codex entry for the register_post_type function. The one parameter we want to focus on is the “has_archive” parameter. This allows us to create an archive page to display these posts.

Step 5: Save and Upload

After you save and upload, this is where the errors would become apparent. When you are adding big chunks of code.

Step 6: Displaying the Custom Post

If you are following with the Smashing Magazine tutorial, skip down to “Displaying your content.”

We could create a custom archive page for our new custom post and then we will be able to view our posts in one central place (almost like a blog roll for our custom post type).

However, WordPress will automatically route us to an archive of our posts if we use the name of our post type (Links) at the end of the URL for our WordPress site (http://www.mysite.com/links). It will automatically use our archive.php file. The routing sets the data context to our custom posts.

If we wanted to create a custom archive page (which would be pretty reasonable) then you could simply create a PHP document named archive-links.php or if you have a different name of the custom post it would be archive-[custom-post-name].php, and then add the appropriate code (probably copied from the existing archive.php file and then modified).

Custom Page Templates

WordPress Codex - Page Templates

The Tuts+ Tutorial below gives a great account of a use case for custom page templates.

A perfect example of a popular use for a custom page template is a ‘full-width’ page. A vast majority of WordPress templates have two or three columns: one ‘main content’ column where post/page content is held, and one or two sidebars that display widgets and calls to action. Sometimes a user will want to take advantage of the full-width of the container those columns are held within, and choose to omit the sidebar column(s) in favor of increasing the size of the ‘main content’ column. Pages that feature media such as image galleries or videos will often benefit from this type of custom page template.

Tuts+ - Creating Custom Page Templates

As a sidenote, sometimes a conditional statement or a custom field could serve you better than creating an entire new template page. Custom page templates are more useful for layout type customization while conditional statements and custom fields can ensure that you have content displaying where you want it too.

For our custom page template, we are going to create a full width template.

Tutorial: Adding a Custom Page Template

Step 1: Create a file

The first step will just be to create a file in our template.

Create a `page_fullwidth.php` file in your theme's root folder

The naming conventions for page templates is often the word “page”, an underscore, and then the word describing the template. So I am going to create this file named page_fullwidth.php. This is not mandatory but it is good to remain within conventions.

This file must be placed within your theme directory for WordPress to read it.

Step 2: Add the Identifying Code to the Template File

The only mandatory part of a custom template file is this bit of code:

page_fullwidth.php

<?php 
/* 
Template name: Full Width 
*/ 
?>  

This registers the custom template with WordPress automatically (it works simply and easily!)

Of course this alone will not work because it does not give any code for the content. The easiest way to fix this is to copy the page.php code, paste it in this custom page, and edit it from there.

Step 3: Copy the Page.php Code into our Custom Template

Just open up your page.php file and copy it into the page_fullwidth.php file. It should look like this now:

page_fullwidth.php

<?php 
/* 
Template name: Full Width 
*/ 
?>
<?php get_header(); ?>
<section class="row">
	<div class="nine columns">
	<!-- BEGIN PAGE PHP -->
            <?php if (have_posts()) : 
                /* OUR DATA CONTEXT IS DEFINED  */
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile;
            endif; ?>
	<!-- END PAGE PHP -->
	</div>
    <!-- Begin Sidebar Area -->
    <div class="three columns">
        <?php get_sidebar(); ?>
    </div>
    <!-- End Sidebar Area -->
</section>
<?php get_footer(); ?>  
Step 4: Make the Page Template Full Width

Our custom template is now identical to our default page template, so let’s make it into a full width template using our Skeleton framework and get rid of the sidebar.

I am also going to add a custom class to the wrapper in case we want to make changes to the CSS for this page only. Adding a class in a template and rules in our CSS file allow us to keep our code separate and clean.

page_fullwidth.php

<?php 
/* 
Template name: Full Width 
*/ 
?>
<?php get_header(); ?>
<section class="row full-width-class">
	<div class="twelve columns">
	<!-- BEGIN PAGE PHP -->
            <?php if (have_posts()) : 
                /* OUR DATA CONTEXT IS DEFINED  */
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile;
            endif; ?>
	<!-- END PAGE PHP -->
	</div>
</section>
<?php get_footer(); ?>  
Step 5: Save and Upload Files

We should upload the page_fullwidth.php file to our theme folder.

Step 6: Enable the Page Template on our Site

The last step of the tutorial is to enable the template in an existing page. Let’s first create a page with some filler content (Lorem Ipsum).

Next, let’s go to the Page editing page and change the Template under the “Page Attributes” panel to “Full Width.”

If you don’t see the “Page Attributes” panel, then you have to click on “Screen Options” at the top of the page and then check the “Page Attributes” box.

You can apply the idea of a Custom Page Template to any number of other scenarios where layout needs to be modified.

Using MetaData and Custom Fields

When working with any CMS, there is likely going to be a need to expand the CMS’s functionality from its core. One thing you may want to add to a CMS is custom fields to place content into the page/post from the user admin. Some use cases for this would be to add a location, a sub-title, another featured image or literally any other item of data that you can imagine.

We have already talked about metadata and have some understanding of how broad the overarching concept of data about data can be. Through custom fields, we are able to use and implement functionality from the metadata. Custom fields are insanely powerful if you consider the scope of what you are able to do - which is essentially limitless. However, there is always the other side of the coin: inserting custom fields requires additional labor by and training of the content manager. Make sure you consider the client and their abilities - and also make sure you implement the custom fields with sufficient error proofing.

https://codex.wordpress.org/Custom_Fields

Shortcodes

Shortcodes are a great way to integrate high level functionality into the WordPress admin directly. Many plugins use shortcodes as a means for displaying their generated content. You can also use shortcodes as a means to integrate your own custom functionality into WordPress.

From the WordPress Codex:

The Shortcode API makes it easy to create shortcodes that support attributes like this:

[gallery id=”123” size=”medium”]

The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.

https://codex.wordpress.org/Shortcode_API

If you see a snippet of code in WordPress that is surrounded by two brackets ([]) then it is likely that you are dealing with a shortcode. The way they are used are defined by the function that created it.

Further down in the jQuery slider tutorial we will briefly include a mechanism to use shortcodes so you can see a tangible example.

Tutorial: Using Shortcodes

Coming Soon

Integrating Outside Resources

In Chapter 7 we discussed the ways to link to a CSS or JavaScript file in WordPress.

There are three ways to link to “outside resources” in WordPress:

  • Use a link in the header
  • (For CSS) Use an @import in the stylesheet
  • Use WordPress to enqueue the files and to handle dependencies.

Each of these methods has it ups and downs. Each of these methods has a compelling use case and when you are linking to files you should consider which method is best.

Linking in the header is the most common and oldest way of integrating outside resources into the web page. This generally looks like this:

<script src='javascript.js'></script>
<!-- OR -->
<link rel="stylesheet" type="text/css" href="stylesheet" />

The other way to do this is to use an @import in the stylesheet for CSS files. This usually looks like this:

@import url(stylesheet.css);

The third way, enqueuing files, was covered in the previous chapter and is a convenient way to organize files and deal with dependencies, but is a bit more time intensive with a slightly higher learning curve.

As an example, I will demonstrate how to add a custom font using Google Fonts.

Tutorial: Custom Fonts

Step 1: Find the Font you Want

Google Fonts is a good place to find free fonts in a wide variety. There are numerous other services which allow for font integration (most paid), but for this tutorial I am going to use Google Fonts.

Navigate to Google Fonts and select a font you like. After you select the font, click on “Review” towards the bottom. If everything seems okay, click “Use.” Check the boxes for the variety of weights and variants that you will use. Remember that the more you choose the more site speed impact the font will have.

Google Fonts gives you three ways to link to the font:

  • The header linking method
  • The @import method (which we will use)
  • The JavaScript insert method (probably the better choice…)

Copy the @import code from the “Use” tab and paste it into your style.css file. Here is an example of what it should look like:

style.css

@import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600,700,300);

Step 3: Add the Font Family to your Webpage

Assuming you will only want one font for your whole site, let’s add the font to our body in our style file.

style.css

body, html {
  font-family: 'Open Sans', sans-serif;
}

You can find the font-family code on the Google Fonts page. They make it as easy as possible for you.

Step 4: Save and Upload

Tutorial: Enqueuing Files in WordPress

We have learned a few ways to include files in WordPress using means that you could use in any web application. However, it is possible to enqueue files through the functions file to do so dynamically. This can be useful when you are not needing a file on every page of your site. Additionally, in WordPress, you can specify any dependencies that the script may need. Hopefully you can see how useful this can be.

We are going to implement a jQuery slider. Sliders generally have little UI value and are pretty out of style for web development, but they are a common element that is frequently requested (in spite of what I have just said) and also make for a good example for integration.

I will use unslider which is the first slider I got when I googled jQuery Slider.

Step One: Gather Dependent Files

Let’s first download the unslider.js file (minified) and then place it into a subfolder in our theme titled “js”.

1. Download unslider.js file

2. Create “js” folder in our theme

3. Place unslider.js file into our theme/js/ folder. 

Step Two: Enqueue the Unslider File

We are going to open our functions.php file and use a WordPress function called wp_enqueue_scripts to load the file dynamically. If you want to learn more about this function and some additional (and cool) things you can do to make it more dynamic yet, go to the WordPress codex entry for wp_enqueue_scripts.

functions.php

<?php
function enqueue_unslider() {
    wp_enqueue_script(                                // function to enqueue script
    'unslider',                                       // name of our script (id)
    get_template_directory_uri() . '/js/unslider.js', // file loc
    array('jquery'),                                  // dependencies
    '',                                               // version - left blank
    true                                              // load in footer
  );
}
add_action('wp_enqueue_scripts', 'enqueue_unslider');
?>

What is happening here should be familiar to you from the other code we have put into the functions file in the past, but I will walk through this because there are other new things here.

  1. We create a function to house our behavior.
  2. We use the WordPress function to enqueue the script.
  3. Input some parameters that the functions wants/needs. Note the dependencies array - where we are adding jquery to our enqueuing dynamically.
  4. Close out the function and then use the add_action function to make it work.

Step Three: Save and Upload

You should be able to see the unslider file loading now.

Step Four: CSS Files Too!

You can also use this method for CSS files too. All you have to do is point to the CSS file and this will work.

functions.php

<?php
function enqueue_randomcss() {
  wp_enqueue_script(                                 // function to enqueue script
    'random-css',                                    // name of our script (id)
    get_template_directory_uri() . '/css/random.css' // location of the file
  );
}
add_action('wp_enqueue_scripts', enqueue_css);
?>

Tutorial: Properly Enqueuing jQuery in WordPress

WordPress comes default with a copy of jQuery. However, that copy is not always the version that you may want/need. In the case of the unslider plugin we added in the previous tutoral, we will need to use a different version than the default one that WordPress uses.

We are going to change the version of jQuery loaded by deregistering the WordPress default and modifying WordPress to include the latest jQuery version.

functions.php

<?php
wp_deregister_script('jquery');

wp_enqueue_script('jquery', 'http://code.jquery.com/jquery-latest.min.js','','',true);
?>

What we are doing here is first removing the jQuery default script using the wp_deregister_script function and then using the wp_enqueue_script to include the new version of jQuery in its place. Make sure to add this higher than your unslider code in WordPress because we want it to load before the unslider.js file does.

Child and Parent Themes

The concept of a child and parent theme is generally available in almost every CMS. In WordPress they are a useful tool to maintaining structure in a template where there is multiple versions of a site with one overlying template.

We won’t over-discuss Child and Parent Themes in this book, but will have a slight overview for informational purposes. It is important to know about from a conceptual standpoint.

A child theme is essentially a separate file structure that references a parent theme. Child themes were created for making modifications to a theme, specifically one that is commercial in nature. The parent will be a fully operational theme in and of itself, but the child theme will modify the styles/structure of the parent theme for its own purposes.

Child Themes

Tuts+ - Child Themes in WordPress

Using a child theme has many advantages, including:

  • Child themes can be a great way to ensure that you are not modifying a theme that would otherwise be updated to a point where it will become un-updatable.

  • Allows the user to do any number of things – including distinct multisite features – while allowing the admin to maintain a strong template infrastructure.

  • If we create a child theme we will not need to create a new theme from scratch which will translate into faster development time.

There are a lot of free and commercial theme frameworks available which give us a wide range of functionality will not need too much customization in our child themes.

If we use child themes as opposed to directly modifying the parent theme to suit our needs, we will easily be able to upgrade to a newer version of the parent theme without losing any of our customization.

A lot of times parent themes not only provide the design but also include widgets and plugins which can be directly used if we create a child theme of that parent theme.

If it’s a popular parent theme you are using, either free or commercial, it’s more likely to have fewer bugs and be more stable as it has been used and tested on multiple sites. Some of the disadvantages of child themes are:

  • A lot of the theme frameworks are very extensive and provide a lot of features which might not be useful to you. This makes frameworks complex and it would increase the time taken to learn and master the framework.

  • It may also affect performance with multiple server side lookups and redundant or unused files.

In the more general outlook of CMSs, the idea of having themes that are subservient to a main theme is extremely common. From a conceptual standpoint, WordPress itself is the parent and the theme is the child – though they obviously perform different functions. With many commercial CMSs though, the parent may hold many styles and functions that will need to be modified. Considering the structure of a CMS with the idea of parent/child or master/servant in mind will help you understand where to make changes and how they may affect a larger scheme.

CSS Based Tutorials

Tutorial: Styling the Search Bar

The search bar is a really important tool for websites from a usability and functional UI standpoint. If you have a moderate to large size site, users will likely rely on this as one of the primary means of finding information.

Let’s work on styling the search bar on our site so that it is a bit prettier and also so that you will know how to style it in your own way later on.

A lot of the code for this tutorial comes from the WordPress Codex entry for get_search_form.

Step One: Locate the Search Bar and Create a File to Modify it

First, let’s note where the search bar is located. Earlier when we created our theme, we included it in the header.

WordPress is loading the search form based off of its default settings. In order to create a better search form that suits our needs, we are going to recreate the search form and include it in our theme folder.

Create `searchform.php` file and put it in your theme’s root directory

Step Two: Add Code and Modify searchform.php

WordPress will now use our newly created searchform.php in place of the default search form. Let’s add some code so that something will start to show up.

searchform.php

<form role="search" method="get" class="search-form" action="<?php echo home_url( '/' ); ?>">
    <label>
        <span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span>
        <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
    </label>
    <input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
</form>

This is the default for HTML5 in WordPress. Knowing what is happening here could be interesting from a knowledge standpoint so feel free to delve into the GET method and how it works in search forms.

Step Three: Modifying the Search Form for our Purposes

The code for the Search Form is pretty solid for our purposes. We are going to add a CSS class to the code so that we can target it in the way we want.

searchform.php

<form role="search" method="get" class="search-form wie-search-form" action="<?php echo home_url( '/' ); ?>">
    <label>
        <span class="screen-reader-text"><?php echo _x( 'Search for:', 'label' ) ?></span>
        <input type="search" class="search-field" placeholder="<?php echo esc_attr_x( 'Search …', 'placeholder' ) ?>" value="<?php echo get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" />
    </label>
    <input type="submit" class="search-submit" value="<?php echo esc_attr_x( 'Search', 'submit button' ) ?>" />
</form>

Now that we have the classes identified, we can add CSS to make it look how we want. I am going to just get rid of the screen reader text in a way that will still allow it to be actually readable by a screen reader but not displayed by the browser to the average viewer. Note that this way of getting rid of content on a page is prefered to using display:none;.

style.css

.wie-search-form .screen-reader-text {
    visibility:hidden;
}

Step Four: Save and Upload

This area is optional and significantly changes the functionality of the UI

Let’s say you want to make something more graphically interesting. We are going to add the Font Awesome package to our site so that we are able to use a bunch of cool icons relatively easily.

It may seem excessive to add a whole css library for only one icon, but having the Font Awesome library in place allows us to use the other icons without even worrying about load time. Additionally, the Font Awesome CSS file often caches and the load time isn’t all that bad when you have a visitor making repeated visits to your site. To make things better, there is even a content delivery network (CDN) link so that the load time is alleviated by allowing a concurrent connection.

Let’s add a link to Font Awesome into our header.

header.php

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

Upload your header.php file and you will see that the font-awesome.min.css file is loading when you refresh your page.

Now, lets replace the searchform.php content and add some CSS rules.

We are going to leverage our Skeleton grid to lay out the search form. Notice how we are using the wie-hide utility class on the elements we don’t want to see.

searchform.php

<div class="row">
    <div class="nine columns">
        <form role="search" method="get" class="search-form wie-search-form" action="<?php echo home_url( '/' ); ?>">
                <span class="screen-reader-text wie-hide"><?php echo _x( 'Search for:', 'label' ) ?></span>
                <input type="search" class="search-field wie-search-field" value="<?php echo get_search_query() ?>" name="s" />
            <input type="submit" class="search-submit wie-search-submit wie-hide" value="" />
        </form>
    </div>
    <div class="three columns search-bar-icon">
        <i class="fa fa-search fa-2x"></i>
    </div>
</div>

Replace all of the Search Bar CSS you have added thus far. Since we are getting rid of some of the elements, we will want to modify the whole thing.

style.css

/*--- Search Bar CSS ---*/

.search-bar-icon { 
    border: none; 
    color: #666; 
    text-align: center;
    padding: 5px; 
    background-color: #fff;
    margin: 0;
    min-height: 45px;
    border-top: 1px solid #666;
    border-bottom: 1px solid #666;
    border-right: 1px solid #666;
}
input[type="search"] {
    border: none; 
    border-top: 1px solid #666;
    border-bottom: 1px solid #666;
    border-left: 1px solid #666;
    min-height: 45px; 
    font-size: 1.2rem;
    padding: 0;
    width: 100%;
    border-radius: inherit;
    margin:0;
    background-color: #fff;
}

Now upload your files and you should have a search form with a search icon. Feel free to mess around with this to get your own desired result.

Tutorial: Sticky Header Bar

A very common element on websites is a sticky element on the page. We are going to use CSS only to make our header attach to the top of the page no matter what. There are more sophisticated methods using JavaScript, but for our needs we can get away with just using a few lines of CSS.

Essentially, we are going to use CSS’s positional elements (fixed) and then add values to the header element to make it fit in a way that is pleasing from a visual and UI standpoint.

Step One: Wrap the Header

header.php

<div class=”header-container”>
  <!-- Put your header content here -->
</div>

Step Two: Modify the CSS to Make it Work

style.css

.header-container {
  width: 100%;
  position: fixed;
  top: 0px;
  z-index: 2;
}

Each rule here has its own purpose: The width makes sure it takes up the entire width of the window; the position: fixed tells the browser to make the div fix to its location on the screen; top: 0px tells the distance from the top of the browser and; z-index is the value of the z parameter which control which items are on top of other items.(the default is 1 so a 2 would make it on top of everything else).

Step Three: Add Other Styling to the Header

You can feel free to add other styling to the header to make sure it looks how you want. Here are some “ideas:”

style.css

header {
  height: 50px;
  background: #F0F0F0;
  border-bottom: 1px solid #CCC;
  margin: 0px auto;
}

#### Step Four: Save and Upload

Tutorial: Circular Images

This isn’t even a difficult thing to do so I won’t even make it like tutorial. There is a CSS-only way to make images appear to be circular.

As an aside, it helps if the image has a square format so tht there isn’t too much cut off. In WordPress you can set your thumbnail size to be square and then apply this style to it to give the circular image effect.

<img src="imagelocation" class="circular-image" />
.circular-image {
  border-radius: 50%;
}

See! Super easy.

If you want to make it even more error proof, you can add some other classes to ensure that it works more uniformily.

<img src="imagelocation" class="circular-image profile-image" />
.circular-image {
  border-radius: 50%;
}

.profile-image {
  height: 150px;
  width: 150px;
  overflow: hidden;
}

See how I used two classes to ensure that I can reuse either bunch of code however I wish?

Tutorial: CSS3 Animation Integration

There are hundreds of different CSS only animations you can use to easily add some interesting UI to your site.

Here are some useful links to expand your knowledge:

A Beginner’s Introduction to CSS Animation - WebDesign Tuts+

animation Property - CSS Tricks

CSS3 Animations - W3Schools Five Ways to Animate Responsibly

Add a Hover Effect to a Menu

First we are going to add some different CSS animations to our menu - which is a great place to encourage and emphasize interaction (thus improving click-through rate).

Let’s start with a simple menu structure. If we are building this menu dynamically, you can imagine that the code below is how it might exist after it is rendered server-side.

<ul class="menu-container">
    <li class="menu-item">Item One</li>
    <li class="menu-item">Item Two</li>
    <li class="menu-item">Item Three</li>
    <li class="menu-item">Item Four</li>
</ul>

Below you can see just one of many different CSS3 properties. Here we are using the transform property to scale the object 1.2 times bigger on hover.

.menu-item:hover {
    -webkit-transform: scale(1.2);
    -ms-transform: scale(1.2); 
    transform: scale(1.2);
}

Adding a Hover Effect to Our Images

Images are used a LOT and they can be both instructive and pretty. As far as being a UI benefit though, they rarely perform up to their potential. For our site though, we are going to want to let users know that some images are just there as content, while others are links (and thus interactive). We could do this a dozen or so ways, but let’s an animation where if you hover over an image that is a link, it moves on the page a bit.

Sample HTML:


<a href="Link to Anywhere"><img src="image source" alt="image description" /></a>

Our CSS:


a img:hover {
    box-shadow:
        1px 1px #999,
        3px 3px #999,
        5px 5px #999;
    -webkit-transform: translateX(-5px);
    transform: translateX(-5px);
}

This CSS will add a box-shadow to any image on the site that is also a link.

Using Keyframes to Define Animation Behavior

The other examples were very simple methods for animating object, but CSS3 animations are much more powerful than simple hover effects. I must include a warning here which is this: don’t overdo the animations in your site. A good, subtle animation can make the site come alive but a busy, distracting animation can make the site look cheap and gimmicky.

CSS Tricks - Keyframe Animations

Let’s define a simple keyframe animation and then consider some other applications. We are going to add a color variety to a button when you hover (I know… more hover…). As a note, you can use keyframe to define any number of other functionalities other than effects.

/* Define the Animation */
@keyframes button-rainbow {
    0%   {background-color: red; left:0px; top:0px;}
    25%  {background-color: orange; left:200px; top:0px;}
    50%  {background-color: yellow; left:200px; top:200px;}
    75%  {background-color: green; left:0px; top:200px;}
    100% {background-color: blue; left:0px; top:0px;}
}

/* Add the Animation and Properties to the Object */
.rainbow-button:hover {
    background-color: purple;
    animation-name: button-rainbow;
    animation-duration: 4s;
}

Adding Advanced Functionality

This area is for various tutorials related to WordPress functionality.

Tutorial: Integrating a jQuery Slider

Earlier, we enqueued a jQuery plugin called Unslider and made sure our jQuery was set to the latest version. If you haven’t done that yet, please reference the Enqueuing Files in WordPress lecture.

We are going to go through this tutorial very methodically, but this is because it is very important that we consider the order in which items are loaded into the page. I will first outline the order of the components and then we will go on adding the code to our footer. You can see the Unslider tutorial here.

<!-- First is our slider CSS-->
<style type="text/css">
     .unslider{overflow:auto;margin:0;padding:0;}
     .unslider-wrap{position:relative;}
     .unslider-wrap.unslider-carousel>li{float:left;}
     .unslider-vertical>ul{height:100%;}
     .unslider-vertical li{float:none;width:100%;}
     .unslider-fade{position:relative;}
     .unslider-fade .unslider-wrap li{position:absolute;left:0;top:0;right:0;z-index:8;}
     .unslider-fade .unslider-wrap li.unslider-active{z-index:10;}
     .unslider li,.unslider ol,.unslider ul{list-style:none;margin:0;padding:0;border:none;}
     .unslider-arrow{position:absolute;left:20px;z-index:2;cursor:pointer;}
     .unslider-arrow.next{left:auto;right:20px;}
</style>

<!-- Second is our "Banner" slider code -->
<div class="my-slider">
    <ul>
        <li>My slide</li>
        <li>Another slide</li>
        <li>My last slide</li>
    </ul>
</div>

<!-- Third we include jQuery -->
<script src="//code.jquery.com/jquery-latest.min.js"></script>

<!-- Fourth we include the Unslider.js -->
<script src="path/to/js/files/unslider.js"></script>

<!-- Lastly we use a javascript function to initialize the unslider behavior -->
<script>
    $(function() { $('.my-slider').unslider({
        autoplay: true 
        });
    });
</script>

Make sure everything is in the correct order you’d want it parsed in. If you are having trouble with this, just inspect your page and look for 1. a console error or, 2. make sure the code is loaded in this order. Okay, let’s proceed.

Step One: Add Unslider Initiation

At the bottom of the footer.php file we will add the initiator for unslider.

footer.php


</div>
    <?php wp_footer(); ?>

<!-- Begin Unslider Initiator -->    
<script>
    $(function() { $('.my-slider').unslider({
        autoplay: true 
        });
    });
</script>
<!-- End Unslider Initiator -->

</body>
</html>

Note how we placed it ALL the way at the bottom so that it is the last thing our page loads. We can also use other javascript techniques to ensure that it loads after the page loads, but for now we will use this method.

Upload this file and ensure that everything is in order.

Step Two: Adding Filler Unslider Code

Let’s work right out of our index.php file for now, though this code should be completely transferable.

index.php

<div class="my-slider">
    <ul>
        <li>My slide</li>
        <li>Another slide</li>
        <li>My last slide</li>
    </ul>
</div>

and our CSS…

style.css

.unslider{overflow:auto;margin:0;padding:0;}
.unslider-wrap{position:relative;}
.unslider-wrap.unslider-carousel>li{float:left;}
.unslider-vertical>ul{height:100%;}
.unslider-vertical li{float:none;width:100%;}
.unslider-fade{position:relative;}
.unslider-fade .unslider-wrap li{position:absolute;left:0;top:0;right:0;z-index:8;}
.unslider-fade .unslider-wrap li.unslider-active{z-index:10;}
.unslider li,.unslider ol,.unslider ul{list-style:none;margin:0;padding:0;border:none;}
.unslider-arrow{position:absolute;left:20px;z-index:2;cursor:pointer;}
.unslider-arrow.next{left:auto;right:20px;}

Now let’s load all of our files up and if the text in the index doesn’t slide by, then there is something wrong.

Step Three: Integrating WordPress into the Slider

We are going to make a custom post type in order to create our slides. If you forget the ins and outs of custom post types, reference the Custom Post Type lecture.

functions.php

<?php

function slider_tutorial() {

  $labels = array(
    'name'               => _x( 'Slides', 'post type general name' ),
    'singular_name'      => _x( 'Slide', 'post type singular name' ),
    'add_new'            => _x( 'Add New', 'slides' ),
    'add_new_item'       => __( 'Add Slide' ),
    'edit_item'          => __( 'Edit Slides' ),
    'new_item'           => __( 'New Slide' ),
    'all_items'          => __( 'All Slides' ),
    'view_item'          => __( 'View Slides' ),
    'search_items'       => __( 'Search Slides' ),
    'not_found'          => __( 'No slides found' ),
    'not_found_in_trash' => __( 'No slides found in the Trash' ), 
    'parent_item_colon'  => '',
    'menu_name'          => 'Slider'
  );

  $args = array(
    /*--- Begin Arguments Options ---*/
    'labels'        => $labels,
    'description'   => 'Slides for our Unslider integration',
    'public'        => true,
    'menu_position' => 6,
    'supports'      => array( 'title', 'editor', 'thumbnail', 'excerpt'),
    'has_archive'   => true,
  );

  register_post_type( 'slider', $args ); 
}

add_action( 'init', 'slider_tutorial' );

?>

This will allow us to have a special post type to loop through. Upload the funtions file and verify that everything works correctly. You should see your post type in your WordPress Dashboard.

Step Three: Integrate the Custom Post into the Slider Code

Let’s set up the HTML for our post type and then we can set it up as PHP loading from our new post type.

index.php

<div class="my-slider">
    <ul>
        <li style="background-image: url('slide01.jpg');">
            <div class="slides-message">
                <h1>Slide One Title</h1>
                <p>This is where the excerpt for the slides will go</p>
            </div>
        </li>
        <li style="background-image: url('slide02.jpg');">
            <div class="slides-message">
                <h1>Slide Two Title</h1>
                <p>This is where the excerpt for the slides will go</p>
            </div>
        </li>
        <li style="background-image: url('slide03.jpg');">
            <div class="slides-message">
                <h1>Slide Three Title</h1>
                <p>This is where the excerpt for the slides will go</p>
            </div>
        </li>
    </ul>
</div>

The good thing about this slider plugin is that it very flexible. If you want to set up your slider differently, consider how you would do that now.

Let’s modify this code to include our custom post type.

index.php

<?php
    $args = array( 'post_type' => 'Slider' ); //Menu item name

    $slides = new WP_Query( $args );
    if( $slides->have_posts() ) {
      while( $slides->have_posts() ) {
        $slides->the_post();
        ?>
          <h1><?php the_title() ?></h1>
          <div class='content'>
            <?php the_excerpt() ?>
          </div>
        <?php
      }
    }
    else {
      echo 'No Slides';
    }
?>

This will generate the content from our custom post. Now let’s integrate this into the code we created above.

index.php

<div class="my-slider">
    <ul>
<?php
    $args   = array( 'post_type' => 'Slider' );
    $slides = new WP_Query( $args );

    if( $slides->have_posts() ) {
      while( $slides->have_posts() ) {
        $slides->the_post();

        /*--- Build Thumbnail URL ---*/
        $thumb_id        = get_post_thumbnail_id();
        $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
        $thumb_url       = $thumb_url_array[0];
        ?>
            <li style="background-image: url('<?php echo $thumb_url ?>');" class="slide-container">
                <div class="slides-message">
                    <h1><?php the_title() ?></h1>
                    <p><?php the_excerpt() ?></p>
                </div>
            </li>
        <?php
      }
    }
    else {
      echo 'No Slides';
    }
?>
    </ul>
</div>

Step Four: Style, Save, and Upload

Here is some sample styling, but you can repurpose this for however you want.

.my-slider { 
  position: relative; 
  overflow: auto; 
  margin-top:25px;
  margin-bottom: 25px;
}

.my-slider li { 
  list-style: none;
}

.my-slider ul li { 
  float: left; 
}

.slide-container {
  height: 300px;
}

.slides-message {
  margin: 50px 0 0 20px;
  padding:20px 0 20px 10px;
  color: #fff;
}

Tutorial: Creating a Separate Blog Page

If you want to use WordPress as a fully functional CMS, you will probably need to separate the blog portion of WordPress into a separate area. There are ways to do this:

We are going to the second option because I prefer it as it is less confusing (for me at least).

Step One: Create a Custom Page

Earlier in this chapter we learned how to create a custom page template. Let’s go ahead and create a new file and populate it with our bare minimum code.

Create a file titled `blog_custom_page.php`

Let’s copy page.php into this file. This will save us time and ensure we have some uniformity to start out with.

blog_custom_page.php

<?php get_header(); ?>
    <div class="row">
        <div class="twelve columns">
            <?php if (have_posts()) : 
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile;
            endif; ?>
        </div>
    </div>
<?php get_footer(); ?>

Step Two: Add the Custom Page Requirements

Since this is technically a custom page template, we need to follow the formalities of that.

blog_custom_page.php

/*
Template Name: Blog Posts
*/
<?php get_header(); ?>
    <div class="row">
        <div class="twelve columns">
            <?php if (have_posts()) : 
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile;
            endif; ?>
        </div>
    </div>
<?php get_footer(); ?>

Step Three: Adding a Custom Query for Posts

The next step is basically about replacing the default code in the page with a custom query for all blog posts. This is a lot like the main index.php page except we need to be explicit about the data context and making sure we handle it correctly.

blog_custom_page.php

/*
Template Name: Blog Posts
*/
<?php get_header(); ?>
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
    <div class="row">
        <div class="twelve columns">
            <?php if (have_posts()) : 
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile;
            endif; ?>
        </div>
    </div>
<?php get_footer(); ?>

If you look at the code closely you can see that the query loads the 10 most recent published pages. It also allows for pagination.

We are going to want to add some navigational links into our code so that this blog page can do everything we need it to as a separate functioning blog roll.

blog_custom_page.php

/*
Template Name: Blog Posts
*/
<?php get_header(); ?>
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
    <div class="row">
        <div class="twelve columns">
            <?php if (have_posts()) : 
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile; ?>
            <!-- Navigation -->
            <div class="navigation">
                <span class="newer"><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span>
            </div>
           <?php endif; ?>
        </div>
    </div>
<?php get_footer(); ?>

We put it at the end of our while loop because we want it to be outside of the loop, but still inside of the if statement about showing posts. If there are no posts then there will be no pagination.

Step Five: Reset the Query

We are going to want to reset the query so that it knows when to stop.

blog_custom_page.php

/*
Template Name: Blog Posts
*/
<?php get_header(); ?>
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
    <div class="row">
        <div class="twelve columns">
            <?php if (have_posts()) : 
                while (have_posts()) : the_post(); ?> 
                    <h2><?php the_title(); ?></h2>
                    <?php the_content();
                endwhile; ?>
                <div class="navigation">
                    <span class="newer"><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span>
                </div>
            <?php endif; 
            wp_reset_query(); ?>
        </div>
    </div>
<?php get_footer(); ?>

Step Six: Making it a Fuller, More Useful Blog Page

So the code above is sufficient for handling all of the needs of the blog page. I am going to add some other code just for error handling and for stylistic efforts. Read through the code so you understand what is happening at each stage.

blog_custom_page.php

/*
Template Name: Blog Posts
*/
<?php get_header(); ?>
<?php query_posts('post_type=post&post_status=publish&posts_per_page=10&paged='. get_query_var('paged')); ?>
    <div class="row">
        <div class="twelve columns">
            <?php if (have_posts()) : 
                while (have_posts()) : the_post(); ?> 
                    <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
                    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <?php the_excerpt(__('Continue reading »','example'));
                endwhile; ?>
                <div class="navigation">
                    <span class="newer"><?php previous_posts_link(__('« Newer','example')) ?></span> <span class="older"><?php next_posts_link(__('Older »','example')) ?></span>
                </div>
                <?php else: ?>
                <div class="404-section">
                    <p><?php _e('None found.','example'); ?></p>
                </div>
            <?php endif; wp_reset_query(); ?>
        </div>
    </div>
<?php get_footer(); ?>

Note how we added some 404 handling and better outlined the post content that will be displayed.

Step Seven: Save and Upload

Tutorial: Integrating Breadcrumbs into your WordPress pages

A “breadcrumb” is a UI tool that allows the user to follow their way through the information architecture in a logical manner. Implementing breadcrumbs in WordPress is a relatively simple task and can add another navigation element. There are several ways to add breadcrumbs to your site. The (possibly) easiest way to do this is through a plugin. But remember the ups and downs of plugins? Maybe you want to implement it in an integrated manner.

Step One: Add Code to the Functions File

Let’s start by editing the Functions.php file:

functions.php

/*-------------- Enable Breadcrumbs --------------*/
function add_breadcrumbs() {
    $post_ancestors = get_post_ancestors($post);
    if (count($post_ancestors)) {
        $top_page = array_pop($post_ancestors);
        $children = wp_list_pages('title_li=&child_of=' . $top_page . '&echo=0');
    } elseif (is_page()) {
        $children = wp_list_pages('title_li=&child_of=' . $post->ID . '&echo=0&depth=2');
    }
    if (is_page() && !is_front_page()) {
        $breadcrumb = "<nav id='breadcrumb'><ul>";
        $breadcrumb .= '<li><a href=" ' . get_bloginfo('url') . '">Home</a></li>';
        $post_ancestors = get_post_ancestors($post);
    if ($post_ancestors) {
        $post_ancestors = array_reverse($post_ancestors);
    foreach ($post_ancestors as $crumb)
        $breadcrumb .= '<li><a href="' . get_permalink($crumb) . '">' . get_the_title($crumb) . '</a></li>';
    }
    $breadcrumb .= '<li><strong>' . get_the_title() . '</strong></li>';
    $breadcrumb .= "</ul></nav>";
    echo $breadcrumb;
    }
}

Let’s talk about what is happening here. First, we are initializing a function named add_breadcrumbs that is going to be the place for our function to operate.

We are then going to use the WordPress function get_post_ancestors to generate an array of the subpages and the page hierarchy. The next conditional statement checks to see that there is anything worth executing - to avoid errors. The conditional statements after that are where we are generating our actual output depending on the array values we received from the get_post_ancestors function. We then iterate over the various values to generate a single output variable $breadcrumb.

Step Two: Add Code to Page

Next, let’s add the function we just created to our page.php file:

page.php

<?php add_breadcrumbs(); ?>

By adding this function we created, we are able to insert the functionality we created in step one anywhere on the site - and it will react dynamically.