Visual Form Builder

Those of you familiar with the UA WordPress Theme have probably seen the contact form shortcode. It’s a basic contact form with a couple of customizations.  For most people looking to add a contact form to a web page, the shortcode does the job.  However, when you want a custom form things can get more complicated.  I have recently built a new plugin that I hope will make things a bit simpler.

Visual Form Builder is a free WordPress plugin that lets you dynamically build forms using a simple interface. Every form includes jQuery validation and a basic logic verification system as well as entry tracking.

A simple script

This plugin started out not as a plugin, but as a relatively simple PHP script that programmatically output the appropriate form code based on what fields and requirements I needed.  This first attempt wasn’t a failure by any means, but it did use some convoluted methods to construct the form.  If I had stopped here, I could have used the tool for a while and been happy with it because it was significantly faster than manually building a form.

The problem with this script was that it was something that really only I would be able to use and my goal was to create something that my co-workers at Web Communications and perhaps others within the UA web community could use.

With that in mind, I decided to turn the script into a form builder plugin for WordPress.

Building a form builder

Having released several other plugins in the last year, getting this one started was fairly straightforward.  Before I began building, I mapped out the requirements I hoped to meet:

  1. Use WordPress HTML/CSS for the admin panel to reduce design maintenance and present familiarity to the user.
  2. Make it easy to add form fields.
  3. Include support for fieldsets.
  4. Order form fields using a drag-and-drop interface.
  5. Use jQuery Form Validation to validate clientside.
  6. Don’t use a CAPTCHA system for anit-SPAM verification.
  7. Log all form submissions in the database.
  8. Export entries to a CSV.

With these features in mind, I began coding.  Not all of these features made it into the first version, but they are there now.

Certainly there are some other form builder plugins available for WordPress, including some commercial tools that offer a wide range of features.  The idea behind Visual Form Builder was to provide a quality, free alternative to the UA web community (or anyone else who finds it useful).

How do I use Visual Form Builder?

I’ve tried to make it as easy as possible to add and customize a form and have even added some help text to the contextual help tab at the top of the plugin page.  Here’s a quick primer on creating your first form.

  1. After downloading, installing, and activating the plugin, go to Settings→Visual Form Builder.
  2. Click on the + tab, give your form a name and click Create Form.
  3. Click the form fields from the box on the left called Form Items to add it to your form.
  4. Edit the information for each form field by clicking on the down arrow.
  5. Drag and drop the elements to put them in order.
  6. Customize the Email Details and Confirmation
  7. Click Save Form to save your changes.
  8. Copy the shortcode from the box on the left called Form Output
  9. Paste into any Post or Page and save your changes

If you have other questions, you can check the FAQ or leave me a comment.

Download it now and let me know if you have any suggestions, bug reports, or feedback.

WordPress Plugin SVN Tip: How to Resolve the ‘Last Updated’ Issue

One of the recurring issues that seems to pop up for WordPress plugin developers as of late is the “Last Updated” problem. For those of you that don’t release your plugins on the WordPress plugin repository or haven’t noticed when downloading a plugin, there is a bit of information right below the download button called “Last Updated.”

Essentially, this date is an indicator of the last time a version of the plugin was released. A big issue for a lot of developers lately is when releasing a new version of their plugin, this date will not update and continue to use the previous version’s date.

Now, this isn’t really a huge deal because users who have a plugin installed will be notified when there is a new version through their site’s admin panel. However, what most plugin authors want, though, is to be listed in the Recently Updated section on WordPress.org. This equals exposure, which equals downloads and more active users.

To solve this problem is pretty simple, but something that isn’t clear because of the lack of communication from whomever controls the Plugin Repository.

With each plugin SVN, you should have three folders: branches, tags, and trunk. Typically, when uploading a new version of your plugin you will place everything into the trunk folder. In addition, you will also copy these files into a new folder under tags with the appropriate version number. The problem lies in how you actually commit your updates.

The Wrong Way

  1. Update your plugin and commit the changes to trunk
  2. Copy these files into a new folder under tags and commit

The reason this is wrong is because the “Last Updated” date reflects whatever is in the tags folder. If the new version’s tags folder does not exist when you update your trunk, it will not be able to find the most recent date. I can’t be sure on this part and it’s only a guess, but I think committing your tags folder at this point causes a bug in the SVN to never look for it.

The Right Way

  1. Update your plugin in the trunk folder
  2. Copy these files into a new folder under tags
  3. Commit ALL changes (trunk and tags) at once

This kind of commit should indicate to the SVN that there is a new version.  From here, it will build the download, update the information (including the Last Updated date), and populate the Recently Updated section.

If there’s some SVN guru out there that can explain to me why it needs to happen this way, please do. All I know is that this needs to be the process a plugin developer must take if they want their work to be hosted on the Plugin Directory.

UPDATE: Otto officially responds on WordPress StackExchange with an answer.  Basically, there is a problem and he’s been trying to fix it.

Programming 101: How to Create Groupings

If you are new to programming, there may be certain solutions that escape you completely, depending on the problem you are trying to solve.  Sometimes it’s as simple as not knowing of a function or syntax.  Other times, it’s a little more complex because it involves logic.

What is Programming Logic?

Before we dive into code, I want to briefly explain what I mean when I say logicProgramming is essentially using code to creatively solve a problem.  Throughout your code could be a logical set of instructions that determines when to execute certain pieces. This is conditional logic.

Many times, the logic to solve a problem is pretty simple:

<?php 
if ( x == 2 ){
    echo 'This is the second record';  
}
?>

Using this kind of conditional logic is essential when you are learning how to program and, over time, will allow you to perform more complex statements.

What is a Grouping?

A grouping is where you sort a set of data into logical sections.  A great example of this is when you see an events calendar that is sorted by date.  There is a single heading for the date and each record that matches that date is listed underneath.

December 10, 2011

  • 12/10/2011 10:00 am – Mary’s Recital
  • 12/10/2011 12:00 pm – Bob’s Cookout

December 11, 2011

  • 12/11/2011 2:00 pm – Computer Science Meetup
  • 12/11/2011 5:00 pm – Art Festival

This sort of breakdown continues on until you get to the end of your data.

How do I make a Grouping automatically?

The above list is easy to create manually, but what do you do when you have hundreds or even thousands of events in a database?  Of course, that’s where programming is going to help us.

Here’s our pseudo code:

  • Query our events database – get all records for the current week
  • Loop through each record and print our information out to the screen
  • If this event’s date is not the same as the previous event’s date, print out our new date heading and continue

Here’s our actual code:

<!--?php<br /-->/* Setup our query - assuming we've already connected to our database */
$query = 'SELECT Title, StartDate, StartTime
FROM events
WHERE WEEK(StartDate) = "12-11-2011"
ORDER BY StartDate ASC, StartTime ASC';

$result = mysql_query( $query );

echo '
<ul>';

/* Loop through our events data */
while ( $row = mysql_fetch_array( $result ) ) {

    /* Assign each row to a variable */
    $title = $row['Title'];
    $date = $row['StartDate'];
    $time = $row['StartTime'];

    /* Handles the date grouping */
    if ( $last != $date ) {
        echo '
	<li class="date_heading">' . date( 'D M d, Y', strtotime( $date ) ) . '</li>
';

        $last = $date;
    }

    /* Output the event name and time below */
    echo '
	<li>' . $title . '-' . $time . '</li>
';
}

echo ';
?>

As you can see, with very little code, we can group our data. What’s even better is that the method can apply to any kind of grouping you need, not just dates! For example, you could have a directory of people and want to group alphabetically by last name (if ( $last != $last_name )). Or, you could have a blog archive page with categories grouped by name and the posts underneath (if ( $last != $category )). There are tons of possibilities.

If you plan to work with a lot of data that needs to be grouped into common headers, save this little snippet of code because it could come in handy.

WordPress & PHP (CCW Part 3)

Working with UA’s WordPress Theme

UA’s WordPress theme makes use of an options panel which is located inside the WordPress dashboard. This allows for a more hands off the code type of customization. There are play by play instructions on how to use the theme located on UA’s Web Guide, http://webguide.ua.edu/wordpress.html, so we won’t be covering that.

What we will be discussing is what a WordPress Theme is composed of and how the system works to display information.

WordPress file organization/main editable pages

When you’re looking through WordPress files, you might want to know which are relatively safe to bring up and edit code wise.

WordPress takes a theme and chops it up so that it can mix and match- separating elements in a way that allows all pages to make use of common parts. (Think of it like a Mr. Potato Head.)

For example: Your header should be the same on every page- regardless of the content. Thus, WordPress takes the header and creates a file called header.php which should contain all your header elements. When you call up a page in your browser, the PHP in the content part of the page calls ‘get_header’ and so the header appears at the top of your page.

Main structural elements:

index.php                your main ‘blog’ page and default home

statichome.php     a homepage that does not have blog style content rotating on it (optional- you make it)

single.php                the base page for all your blog pages or ‘posts’

page.php
                  the base page for all your ‘pages’

sidebar.php            where your sidebar is located

header.php             where your primary horizontal navigation is located

footer.php               where your footer is located

The footer, header, and sidebar will generally have your links and navigational elements. The index, statichome, single, and page will have your content. 

Content structure/hierarchy is shown below.

Structure of a completely built WordPress page is shown below.

The header will contain all your CSS, just like normal as well as your horizontal navigation.

The content page will have php linking it to the header, sidebar, and footer. The content page shown here happens to be the blog index page.

The sidebar contains your secondary links and can be placed within your content page where ever you want it to appear.

The footer will contain all your animation scripts such as JavaScript and its libraries.

PHP in WordPress

This is not a programming course, so we’re not going to dive into the proverbial PHP pool. However, that being said, I do want to give you a few helpful scripts and explain what they do. Why? Well, if you choose to have a ‘statichome.php’ that will do some things in connection with WordPress’ database- well, it just won’t fly the HTML way.

This is where PHP template tags come in. For a complete list, please refer to the WordPress Codex: http://codex.wordpress.org/Template_Tags

Template tags are used within your blog’s .php template pages to display information dynamically or otherwise customize your site. What most tags will do is pull information out of the database. Other tags arrange structure- such as the “get_header” or “get_footer” tags that attach those elements to a page.php or single.php.

Referencing

WordPress has its own database for managing content and information. In order to access the information, a PHP script is needed to make the browser load the info from the database.

In order to reference things housed in the database without knowing the entire location of the object, we use:<?php bloginfo(); ?>

This PHP gets information from the WordPress database.

A practical example and most likely the only time you’ll really use this is for images:

<img src="<?php bloginfo("template_url"); ?>/images/name.jpg" />

Elements you might like to customize display on

Some elements you might want to customize display on would be the date and time.

<?php the_date (); ?>                             <?php the_time(); ?>

You might want something short like “Thu, 21 Dec 2034” or a little longer as in “Thursday 21, December 2034”. So where are the above two examples used? They can be used anywhere- but mostly you’ll see them as ‘date posted’ in blog posts or news releases.

How to use:

<?php the_date (‘m-d-Y‘); ?>        displays:    month-day-year   ex:  08-03-2034

<?php the_date (‘M  d, Y‘); ?>     displays:    month day, year   ex:  Aug 03, 2034

<?php the_date (‘F j, Y‘); ?>       displays:    month day, year   ex:  August  3, 2034

<?php the_time(‘D, g:i a’);  ?>    displays:    day, hour:minutes am/pm  ex: Tue, 9:45 am

<?php the_time(‘l, G:i’);  ?>        displays:    day, hour:minutes  ex: Tuesday, 17:45

For more information on formatting date and time, see: http://codex.wordpress.org/Formatting_Date_and_Time

Within WordPress’ Control Panel

Most organizational customization can be easily achieved within the control panel. One of the major adjustments you’ll make in the control panel is deciding your site’s style.

Site Styles

There are 3 kinds of website homepages available: Blog Style, Static Homepage, or a combination of the two.

Blog Style
By default, WordPress will display the homepage of your website as a blog. For many themes the default will be to use a blog-style homepage.

Static Homepage
If you would like to use a static homepage to give your website a traditional website feel, there are several steps you must take:

  1. Login to your WordPress account and create a new page called ‘statichome’. Only fill in the title box. Leave the rest of the page blank.
  2. To the right is a section called ‘Attributes’. Under ‘Template’ select ‘Static Home Page’ and publish the page.
  3. Make a new Page called ‘blog’ and publish. (Once again, only fill in the title box, and this time do not make any changes in the ‘Attributes’ section.)
  4. Under ‘Settings’ on the main left toolbar, select ‘Reading’.
  5. Select ‘static page’ and set the front page as ‘statichome’ and the posts page as ‘blog’. Then save the changes.

Now when you visit the actual site, your static homepage will show up as the index instead of the blog page.

Static Homepage with Blog Page
If you decide to use a static homepage, but you still want to have a blog on your site elsewhere, all you need to do is include an absolute link to your blog within your main or side navigation. You can find this link by going to the ‘blog’ page that you created above.

HTML & CSS (CCW Part 2)

After you’ve figured out navigation, layout, and sent out requests for content, it’s time to start building your site. This lesson deals with basic HTML and CSS along with best practices using for both.

There are many web editors out there, but for this lesson I’ll be using Dreamweaver’s basic starter page for my example.

Starting on the build

So, let’s have a look at what a blank page looks like in code. A basic Dreamweaver HTML page is shown below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document Title</title>
</head>
<body>
</body>
</html>  

There are six parts here that make up a solid base for your page. Your Doctype, html  tags, head tags, meta data, the title tags, and last the body tags. All are part of the HTML code.

HTML (HyperText Markup Language)

Your HTML is the skeleton for your CSS. It supports the body of your webpage while CSS provides the muscles and skin. Therefore, if your HTML is incorrect, it doesn’t matter if the CSS is perfect, your website will fail.

First off, let’s talk about HTML and XHTML (Extensible HyperText Markup Language). HTML is mainly comprised of tags like the example above. XHTML is not very different from HTML- except that it’s stricter which allows browsers to process the code faster and eliminate errors caused by incorrect markup.

For example, <img src=”example.jpg”> would not display in XHTML because the ‘img’ tag is not closed. To display correctly, it would need to look like this:<img src=”example.jpg” />

Yes, the ‘/’ needs to be at the end of every tag to close it in XHTML.
HTML is not so picky and will take either <img src=”example.jpg”> or <img src=”example.jpg” />.

Generally, it is good to use HTML for your doctype, but practice XHTML within the HTML. Why? Because it’s better for the browser.

XHTML within HTML

By following all the XHTML rules you help the browser load pages faster and it’s less confusing to search through. That’s where XHTML is a plus- however, you may not know all the rules of XHTML, or you might miss a rule by accident, rendering your whole page useless until you find the problem. HTML doesn’t care about little mistakes, so by using XHTML style in and HTML page, you cover accidental code flubs so that your page will still work when you open it.

Some major differences in XHTML and HTML

HTML

<br>      <hr>       <img src="example.gif">
<P>Something</P>

XHTML

<br />      <hr />      <img src="example.gif" />
<p>Something</p>

For more on XHTML rules:           http://www.w3schools.com/xhtml/xhtml_html.asp

HTML Basics

NOTE: I’ll be writing in XHTML, but I use it within an HTML framework. Keep this in mind.

What is a “doctype” and why is it on my page?

First off, the doctype declaration should appear before any other markup on your page. Why? Because it is an instruction to the web browser about what version of the markup language (eg: HTML, XHTML and their variants) the page is written in.

For more on this see:            http://www.w3schools.com/tags/tag_DOCTYPE.asp

Placement

The placement of code in the HTML specifies what elements are within elements and their hierarchy to other elements. For example, let’s say I wanted a box within a header. I would have:

<div id=”header”><div class=”box”>Box Content</div></div>

The ‘div’ tag calls the CSS to place the header on the page and insert the box into the header. It is very important to close your divs as it tells the CSS styling to stop past the ‘</div>’ point. It is also important to nest your tags to avoid conflicting style properties or code errors. To style the elements for each div tag, you must go into the CSS and not the HTML. Remember that most HTML is strictly for organizing.

<head>…</head>

Your ‘head’ tags should contain all information a browser needs to render the content in the ‘body’ tags as well as information pertinent to search engines and browser needs for your page.

Tags used in the ‘head’ are:

<title> ... </title>      displays title of page for the browser to put on the tab or on the window’s title bar
<meta />  gives data for search engines to organize your page by/tells what your page is about
<base />   specifies a default address or a default target for all links on a page
<link />  gets a resource reference such as a CSS style sheet

An example for calling a style sheet is below.

<link rel="stylesheet" href="style.css" type="text/css" media="screen" />

So, what’s going on here?

Well, ‘rel’ says that the relationship between the current document and the linked document is that it’s a style sheet, ‘href’ calls the actual style sheet from its location,  ‘type’ tells us that the style sheet  is formatted in text/css, and ‘media’ tells us that it’s for a computer screen.

If you wanted to make this style sheet for a phone, you would change ‘media=”screen”’ to ‘media=”mobile”’. ‘media’ allows you to have multiple style sheets on a page that target different devices. (ex: style sheets for mobile, print, and screen)

<body>…</body>

Your ‘body’ tags contain the page elements that will show up in the browser window. Organization of these elements is key. Keep your tags correctly nested. I can not stress this enough. Keeping tags well organized in your code will help in a lot of ways.

Some commonly used tags in the ‘body’ are:

<h1> ... </h1>  creates a heading with h1-h6, h1 being the largest and h6 being the smallest
<p> ... </p>    organizes content into paragraphs
<a></a>  designates a link
<img /> places an image within the page
<br /> puts a break in-between text
<hr /> creates a horizontal rule- ie, a line- between elements
<strong> ... </strong>   strong emphasized text (bolds text)
<em> ... </em>  emphasized text (italicizes text)
<ol><li> ... </li></ol>  ‘ol’ is an ordered list, ‘ul’ is an unordered list, ‘li’ in both ‘ul’ and ‘ol’ is a list item
<div> ... </div>  tag defines a division or a section in an HTML document- mostly used to call style elements from the CSS
<form> ... </form>  used to place a form element within the page

Some natural hookups:

There are some tags that naturally have certain things following them.
For example, <a href=”...”> ... </a>.

‘a’ says that it’s a link and ‘href’ tells the link where to go. <img src=”...” /> ‘img’ says that the element is an image and ‘src’ tells the location of the image you want displayed.

Putting together CSS and HTML using ‘div’

The ‘div’ tag when used with CSS will either have ‘id’ or ‘class’ attached to it.

ex: <div id=”...”> ... </div> or <div class=”...”> ... </div>

A ‘div’ can have multiple classes attached, but only one id. Also, a certain id can only be used once on a page where as a certain class can be used multiple times.

ex: <div id=”container” class=”numberone” class=”numbertwo”> ... </div>

BEST PRACTICES

  • Put CSS in the header just above the </head> tag. (In order to have all styles ready for the body when it loads.)
  • Put links to scripts as well as scripts themselves (ex: jQuery, mootools, javascript) at the bottom of the page- just above the </body> tag. (This encourages faster page loading.)
  • Keep things well organized and, when necessary, document where your div tags end like so: </div> <!-- example div ends here -->
  • Nest your tags.

CSS (Cascading Style Sheets)

Getting the look

The main styles of the site, look and layout, are controlled mainly through CSS. If you need to edit the presentation of an element, div, or id use CSS. CSS and HTML together make a website fast loading and easily customizable. Using a CSS style sheet, you can change an element of your site across all the pages that have that element simply by editing your CSS. This cuts down on mistakes and makes your time spent on code more efficient.

CSS Example

Some examples of CSS.

h1 {
font-size: 2.6em;
padding:5px 0 20px 0;
}
#content {
padding-top:15px;
font-family:Verdana, sans-serif;
}
.sec-nav {
padding:0;
margin:0 0 30px 0;
}
li:visited {
color: #00CC00;
text-decoration: none;
font-weight: bold;
}  

Writing style

Before we get into the guts of this operation, I’m going to tell you about how people write the optional parts of code.

There are 3 types of naming conventions:

  • camel case
  • dash
  • underscore

Let’s say I have something in my CSS I want to call “Slider Thumbnails”.   Well, spaces are defined as starting something new, so I can’t use the above. Solution- one of the 3 naming conventions.

Camel Case:      sliderThumbnails

Dash:                  slider-thumbnails

Underscore:      slider_thumbnails

Which do I use? I use underscore because it seems easier to read for me, but this is all subjective. You pick the style that works best for you. What is important is that there are no spaces within the name.

About CSS

CSS can be used in three different ways: inline, internal, and external.

Inline is when you use ‘style’ attached to an element to build CSS for a single element within the HTML.

ex:   <p style=”color:red;”>…</p>

Internal is when you place your CSS styles in the ‘head’ tags.

ex: <head>
<style type="text/css"> p  {color:red;} </style>
</head>

External is when you have a separate style sheet and link to it from the ‘head’.

ex: <link rel="stylesheet" href="style.css" type="text/css" media="screen" />

The external style sheet will have formatting like this inside it: p  {color:red;}

What is a CSS format?

CSS creates a selector for HTML to use when you group elements you want styled on your page. The selector then has notes on what properties you want added and what you want the properties to be.

ex:   selector { property:value; }

There are 2 ways of organizing CSS: single line and multiple line – both are correct so it’s a matter of preference which one you use.

selector { property:value;  property:value; }

selector {
property:value;
property:value;
}

Your selector can be named anything you want. (With the exception of element selectors.)

Different types of selectors

There are different types of selectors: element, id, class, and pseudo.

Element selectors retain their proper html titles such as ‘body’, ‘p’, ‘h1’, ‘ul’, ‘ol’, ‘a’, ‘img’, etc… and do not use any identifying features. ex:  img

Id selectors use ‘#’ before a name and are unique.  ex:   #container

Class selectors use ‘.’ before a name and are not unique.   ex:   .thumbnail

A pseudo selector uses ‘:’ and must be attached to an element selector.    ex:    a:hover

As stated before in the html section, an ‘id’ is unique and the same id can’t be used numerous times on a page. Use ‘id’s for main containers and other large boxes on a page. A ‘class’ is not unique and can be used multiple times on a page or multiple times on an element.

For more on this see:            http://css-tricks.com/the-difference-between-id-and-class/

Property and value

A property in CSS tells what you want to style within the selector and the value tells how you want it styled. For instance, I would like a red boarder around my header.

ex:   #header  {border-color:red;}

“#header” would be my selector while “border-color” would be my property. “red” is the value I want displayed as the “border-color” on the “#header”.

There are many different types of properties. Some deal with position while others handle styles and spacing. For a full list of properties, see http://www.w3schools.com/css/css_reference.asp and scroll down to CSS Properties.

Decoding CSS

Let’s take apart this CSS.

#wordmark{
background:url(images/wordmark.png) top left no-repeat;
width:709px;
height:112px;
position:absolute;
top:0px;
left:10px;
text-indent:-9999px;
margin:0;
}

It’s an ‘id’ named wordmark.
It has a background image placed in the top left and the image is not repeated.
It’s 709×112 pixels, and its position is absolute on the page with the coordinates being top 0 and left 10. It has a text indent of -9999px, which means the text is hidden off the page, and the margin is 0 so other elements will come right up against it.

Most CSS properties are easy to figure out. Especially in things they control. Just use common sense and in most cases- what you think it does it what it does. Some tricky properties are ‘color’, which actually controls the color of your text, and ‘margin’ vs ‘padding’.

Margin determines the amount of space around your element.
Padding determines the amount of space within your element.

Bundle up

Sometimes you want to specify a lot of things that actually all relate to one property. Well, there is a way to do that.

background:#990000 url(images/footer-bg.png) top left repeat-x;
font:bold 1.7em/175% "Lucida Sans",Lucida Sans Unicode,Verdana,Helvetica,sans-serif;
border:1px #ccc dotted;
padding:4px 0 4px 4px;
margin:3px 0px 10px 15px;

This helps lighten your code and makes things run faster. It also makes things easier to find.

BEST PRACTICES

  • Separate your sections with descriptive headers. (ex: /* styles for slider */)
  • Use CSS to style all links and header elements so that they appear the same throughout the site.
  • Watch out for conflicting CSS. In order to remove conflicts, sub list the element when necessary. (ex: #containingDiv h1)

Permalink options for custom post types in WordPress

I recently did some work with custom post types in WordPress. As I finished setting up my first custom post type, the last thing I got hung up on was customizing the permalink settings for the new post type. It’s a really easy thing to do, but it took me a few minutes to figure it out, so I wanted to write a quick post describing the options in case that would help anyone else.

Obviously before you can deal with the permalinks settings for your custom post type, you have to have a custom post type. Today’s article does not address that (at least not comprehensively), but there are plenty of great resources that describe that process. Here are some of the ones that have been helpful to me:

Let’s say you’ve defined a custom post type called “Helpful Hints” with the following settings (this code would go in the functions.php file within your theme):

<?php
add_action('init', 'my_custom_init');
function my_custom_init()  {
register_post_type('hints', array(
	'label' => __('Helpful Hints'),
	'singular_label' => __('Helpful Hint'),
	'public' => true,
	'show_ui' => true,
	'capability_type' => 'post',
	'hierarchical' => false,
	'rewrite' => false,
	'query_var' => false,
	'supports' => array('title','editor','author','thumbnail','excerpt','comments')
  ));
}
?>

As you might guess, the part we need to work with to modify the permalink settings is the rewrite argument. The default of rewrite is true, but in the code above we have it set to false. Having it set as false will disable so-called “pretty URLs” (even if you have “pretty URLs” enabled in your general permalinks settings) and result in your custom posts having URLs like this:

http://www.yourwebsite.com/?post_type=hints&p=323

Remember, the URL above is not the default, but I wanted to show you the “ugliest” URL first and work up from there. As you can see, the post_type shows up exactly as we defined it in register_post_type (hints) and the post ID is added to the query string as well.

If we change the rewrite argument to true, we’ll get this instead:

http://www.yourwebsite.com/hints/how-to-do-something

This is the default when you have “pretty URLs” enabled in your general permalink settings. That is, if we included no rewrite argument in the register_post_type arguments, this is what we would get. Again, remember that the text for the slug (the part after the .com/) will be taken directly from the post_type, not from the label, or the singular label, or anything else.

In most cases, that will probably be sufficient. But suppose for a minute that you don’t want just “hints” to show up as your slug. Let’s say you want something a little more descriptive, maybe something like “helpful-hints.”

You can do this by adding an array that assigns a slug in the rewrite argument:

<?php
add_action('init', 'my_custom_init');
function my_custom_init()  {
register_post_type('hints', array(
	'label' => __('Helpful Hints'),
	'singular_label' => __('Helpful Hint'),
	'public' => true,
	'show_ui' => true,
	'capability_type' => 'post',
	'hierarchical' => false,
	'rewrite' => array('slug' => 'helpful-hints'),
	'query_var' => false,
	'supports' => array('title','editor','author','thumbnail','excerpt','comments')
  ));
}
?>

Since the default value of rewrite is true, we’re already going to have a “pretty URL,” but the slug array gives us a more descriptive URL without affecting anything else as far as labels and such. The result looks like this:

http://www.yourwebsite.com/helpful-hints/how-to-do-something

To review, for a WordPress site that has “pretty URLs” enabled in the permalinks settings, here’s how your custom post type permalinks will display with various rewrite settings:

  • By default: Rewrite is set to true but with no custom slug. The post_type will be used for the slug in the URL.
  • Rewrite set to false: The URL will revert to a query string in the URL that includes the post_type and the post ID. This will happen even if your site has permalinks enabled in the general settings.
  • Rewrite set to true with slug defined: This will result in a pretty URL with any slug you choose.

One final thing to keep in mind here is that anytime you change the rewrite settings in your code, you will need to open your permalinks settings screen in the WordPress Admin panel to flush the rewrite rules. Without doing that, your changes will not go into effect. For more information on this, check out ticket #13022 on the WordPress trac.

WordPress University webinar on Higher Ed Experts

Just a quick announcement about a unique professional development opportunity in the new year…

It’s no secret that we in Web Communications are big fans of WordPress, and we’ve addressed our use of WordPress as a content management system for institutional sites here plenty in the past.  Now we’re partnering with Higher Ed Experts to conduct a webinar on using WordPress in higher education.  The WordPress University webinar is set for March 22, 23 & 24, 2011, and our WordPress guru and developer Matthew Muro will be delivering the second panel, titled “How to create a branded WordPress theme for your decentralized units.”  Other participants include Mike Richwalsky from John Carroll University and Stephanie Leary from Texas A&M University.

If you’re interested in exploring the use of and application of WordPress in greater depth and getting hands-on with using WordPress to manage your college/division/department web site, I’d encourage you to sign up for the webinar – it’s going to be a great class.  If there is interest from multiple areas, we can possibly organize a group session on campus – just let me know in the comments section or shoot me a message.


WordPress University:
Strategies, tools and shortcuts for WordPress-based higher ed websites
March 22, 23 & 24, 2011 – 1PM-2PM ET
More Information and Registration

Restrict Categories – My Experience Writing a WordPress Plugin

Two months ago today I released my first WordPress plugin, Restrict Categories, and in that short time it has already reached over 1,000 downloads.  I thought this milestone was a good chance to write about my experiences developing a plugin.

Background

A couple of months ago, I was doing some research for a project here at Web Communications and it needed to have a particular functionality within WordPress.  We needed to control which categories certain users would be able to edit and post.  At first, I had hope this was possible because I discovered several plugins that appeared to accomplish what I wanted.  However, I quickly realized that none of them worked or didn’t really do what I wanted them to do.  My options were slim: 1) fix one of the broken plugins or, 2) write my own.  After trying to fix a couple of the plugins that had promise, but failing to do so, I started the process of developing my own.

Where to start?

The first place I looked was the WordPress Codex and leaned on it heavily in the early goings.  Specifically, I looked at the Plugin Development pages.  The pages I relied on the most were Writing a Plugin, Adding Administration Menus, Creating Options Pages, and the always helpful Function Reference.

I also think it’s beneficial to check out WordPress Coding Standards, Inline Documentation, Internationalization, and Data Validation.

Initial Development

In very basic terms, this is what I needed my plugin to do:

  • Display a list of all user roles (Administrator, Editor, Author, etc)
  • Display a list of all categories next to each role
  • Allow the plugin user some way to select categories and assign them to that author
  • On the Posts screen, display only those posts with categories from those selected above

Tackling development on this went in pieces.

  1. Create the basics of what I need to get my settings page to show up in the WordPress menu
  2. Get a list of user roles
  3. Get a list of all categories
  4. Combine all of these things on my plugin page and have a process that saves the information to the database
  5. Use that information to filter the Posts screen for restricted user roles

Some of these steps were easier than others and there were many days where I tried one thing, thinking it was the solution, only to be deterred and abandon it for a different route.  But, after a week and a half of trial and error, I finally had a working plugin.

Getting my plugin in the WordPress Plugin Directory

If you’ve ever wondered how people get their plugin on the WordPress.org site, you first start with the Plugin Developer Center.  I signed up and then began my learning process with SVN (Subversion).  Having never used SVN before, I was a bit unfamiliar with where to start or what program to use!  If you are on a Mac, your best bet is to use Terminal.  There are some graphical interfaces that are supposed to make it easier, but I then found it hard to follow the SVN directions from the WordPress documentation.

Anyway, once I figured that out, my plugin was soon live and being displayed in the “Newest Plugins” section.  Very cool.

Improvements

In many ways, Version 1.o had many of the pitfalls that most newbie WordPress plugin developers fall victim to.  In fact, I’m pretty sure I was committing a couple of these Top 10 mistakes.  I was also getting some users with errors.  So, I began troubleshooting my code as well as looking into how to make my plugin better.

For the first couple of revisions, the updates were mainly bug fixes.  Then, I decided to test it in the alpha version of WordPress 3.1.  One of the changes they made to the Posts screen inadvertently would allow a restricted user to bypass all restriction and they could get to a post they weren’t allowed to view.  What was even worse was that I couldn’t figure out how to fix my code to make it work with new Posts screen.  Uh oh.

So, I reached out to the WordPress community asking for a solution.  I asked a question on the wp-hackers mailing list and, when I couldn’t get a workable solution there, headed towards the WordPress Stack Exchange.  Luckily, someone responded with an answer.

I was resistant to the “solution” presented to me at first because I felt I was so close to the answer and was getting the run-around.  What I was really doing was not wanting to do the work to change my code.  However, once I actually took the time to work this solution into my code, I realized it was better.  This wasn’t the last time that asking a question in the community led me to a better solution.

It took two months and 1,000+ downloads to make me a better WordPress developer and a better PHP coder.

Changing the URL of your WordPress site

A question often asked is how to change the URL of their WordPress site.

Here’s a common scenario:  you install WordPress into a sub-directory on your web server so you can create a theme, upload content, and test it without interrupting your current site.  There’s nothing wrong with doing it this way.  In fact, this is how a lot of people develop and test websites before launching, myself included.  One problem many people run into after switching their homepage to point to the sub-directory you installed WordPress is that many of the URLs still use the sub-directory instead of the root.

Let’s look at an example.

At some point development stops and you are ready to switch your homepage so that it’s using the /wordpress/ directory.  However, you notice that something isn’t quite right.  Perhaps the links to your posts are going to the old development URL?  Perhaps your theme was dependent on the old URL and the header image is broken?

This is fixable in two easy steps.

Update URL in WordPress admin panel

The first step is to login to the admin and go to Settings -> General.  Update the WordPress address (URL) and Site Address (URL) options from http://mywebsite.com/wordpress to http://mywebsite.com.

Run MySQL query to update content

The next step is to run a MySQL query.  If you aren’t familiar with SQL, contact your host or IT support to see if they can run it for you.

UPDATE wp_posts SET guid = REPLACE (guid,'http://mywebsite.com/wordpress','http://mywebsite.com');
UPDATE wp_posts SET post_content = REPLACE (post_content,'http://mywebsite.com/wordpress','http://mywebsite.com');

Once you have completed these steps, all URLs should be updated.

If you are performing more complex moves such as moving the database to a different server or moving the WordPress files around, check out these articles on the WordPress Codex: Moving WordPress and Changing The Site URL.

How to make custom page templates in WordPress

In this article, we’re looking at how to set up custom page templates in WordPress. The benefit of using custom page templates is that they allow you to basically build standard web pages that pull their content from the WordPress database. That means the content can be updated by non-technical users through a web form on the WordPress Admin Panel.

When you publish a page in WordPress, the page.php template is used by default. Certainly you can modify page.php as much as you like, but sometimes you want to design something different from this default template. Custom page templates enable you to design dynamic pages that differ from the standard page.php template. You can build and deploy as many of these as you like, so once you understand them, it really opens up a lot of options to customize your WordPress site to meet the needs of your organization.

There’s no point re-inventing the wheel, and lots of good information about this is available in the WordPress Codex. The best place to start for this topic is on the Pages entry. I would recommend reading that entire page and probably checking out some of the other pages linked from there, but here is one important excerpt to get us going:

WordPress can be configured to use different Page Templates for different Pages. Toward the bottom of the Write > Page administration panel (or on the sidebar, depending on which version of WordPress you are using) is a drop-down labeled Page Template. From there you can select which Template will be used when displaying this particular Page.

So, how do you create one of these page templates? Remember that all page template files in WordPress are PHP files, so if you wanted to create a custom page template for a page called Contact, you would start by setting up a file called contact.php. Technically, the only PHP that you must include in this page goes right at the top, where you identify contact.php as the page template with the name of Contact. The code looks like this:

<?php
/*
Template Name: Contact
*/
?>

Once you’ve put that at the top of the contact.php file and uploaded the file, the Contact template (contact.php) will be available for you as a template whenever you create a page in the WordPress Admin Panel. All the page templates that are available will be shown in a dropdown menu to the right of the post box on the Add Page screen in a box labeled Attributes under Templates.

Screenshot of WordPress page template dropdown menuI’ve included a screenshot here of what that dropdown menu looks like. In this example, there are several custom templates to choose from.

We mentioned earlier that the only PHP you technically must have in a custom page template is the snippet above with the Template Name: Contact line in it. The reason that is true is because with that PHP included, the rest of any custom template could be static HTML if you wanted it to be. In practice, you’ll probably often want to be able to add and update content dynamically through the WordPress Admin Panel so there will be additional PHP, but that is not a requirement for a custom page template.

If you do want users to be able to add content for each page in the WP Admin Panel, how do you tell your template where and how to display that content within your custom page template? You do that by including The Loop in your custom page template. There are lots of ways you can style the content from the loop, but here is a very basic version of it:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

	<?php the_title(); ?>

	<?php the_content(); ?>

<?php endwhile; endif; ?>

The above version of the loop doesn’t include any extra CSS hooks and only displays the title and the content for the given page. There are lots of other things you could include such as the_excerpt and the_permalink.

One thing that might be confusing about the loop in the context of pages is the use of the term post in The Loop. You might be thinking that pages are different from posts in WordPress so why are we looking for posts in the PHP here?

Pages are indeed different from posts in WordPress, but as far as how they are treated in the WordPress database structure and the way they are called in The Loop, pages are, in that context, a type of post.

Now that we’re using The Loop to display the content for the given page into our custom page template, we can put whatever we want to put around this content. That means our page can have a standard heading or banner at the top and a footer at the bottom, or basically anything else that you can code up. You can also use more WordPress template tags such as get_header and get_footer to make including that kind of thing more modular.

Once you get used to building and using custom page templates, it becomes relatively straightforward to use WordPress to manage content on almost any type of page you can design.