DIY WordPress: What You Need to Know About PHP if You Don’t Yet Know a Damn Thing

(Reading time: 6 – 9 minutes)

WordPress can be considered a dynamic web application. What that means depends a little bit on who you talk to, and what you are using WordPress to achieve. (Look for related reading at the end of this article.)

What “dynamic web application” means for this article is a web page resulting from an unholy fusion of HTML, CSS, PHP and MySQL. And Javascript. Can’t forget Javascript.

5 different langguages. That’s crazy. Seriously, it’s crazy. Back in the dinosaur days (1990s), it was plenty to master one programming language per application.* You could even spend most of a career just in one or a few languages.

Anyway, if you’re still with me, you probably know a little bit about HTML and CSS by now. It turns out that for WordPress, you don’t need a lot of Javascript or MySQL for tweaking themes and plugins. Helpful, they are, but not necessary.

What you need now is a little PHP, so that’s where we’re going next.

“Why should I care about PHP?”

You continue, despite your better judgement, to read Website In A Weekend on a regular basis. Which means by hook or by crook, you’re at least partly in the do-it-yourself camp. You may not want to camp in DIY, but there you are. So you should care because if you don’t, you’re gonna mess something up sooner or later.

Sidenote: If you whitescreen WordPress, that is, all of sudden, the only thing displayed is a blank white page, you almost 100% surely have a syntax error in your PHP code, and that syntax error is almost surely a missing semi-colon “;”.

And it won’t be pleasant.

So that’s why you should care.

WTH is PHP, anyway?

PHP is a recursive acronym, meaning PHP Hypertext Preprocessor. For more on recursive acronyms, I suggest Wikipedia.

PHP is a programming language that slides in and around HTML to do a lot of tedious dirty work so you don’t have to. PHP code intermingled with HTML often appears ugly. In programming, something appearing ugly often is ugly. One of the weaknesses of PHP is that some of this ugliness can’t be helped. It was designed in.

PHP is a module that plugs into your web server that translates (preprocesses) PHP files into HTML (hypertext). The PHP interpreter is different than the web server. You can run a web server without PHP, but you can’t serve PHP over the web without a web server.

PHP is all that and more!

PHP Hypertext Preprocessor

From the above, PHP the programming language is what’s of most concern to you, right here and right now. The language is what you’re going to see when you’re poking around in WordPress. Here’s the basic concepts.

  • PHP language syntax. PHP syntax derives from the family of C like languages. If you know already know C, you will pick up PHP pretty quick (but you probably already know that). If you don’t know C, no worries, it’s not that important. The point is, there’s history and meaning behind PHP syntax. It didn’t sprout from someone’s forehead, ex nihilo.

    Current versions of PHP are “object-oriented.” But really, PHP is procedural, object-oriented capability was bolted on, not designed in.

  • Understand variable scope. Understanding variable scope is critical. If you have programmed before, you may need to unlearn some assumptions, like global variables not acting how you think they should. Variable scope in PHP still trips me up. If you have little programming experience, you won’t have to unlearn anything. That’s a good thing.
  • PHP paths are critical. When you write an application or even tweak a plugin for WordPress, you need to know how WordPress and PHP find things like files and images you want to deliver to your readers. WordPress does a pretty good job of standardizing paths. Spend the time to figure that out.
  • Understand single and double quoting. Single and double quoting in PHP behave slightly differently, but these small differences are important. Sometimes single and double quotes can be used the same way, other times, they can’t be used the same way. Most people develop their own scheme for when and how to use each type of quoting.
  • WordPress and PHP APIs are different. A collection (library) of functions is called an Application Programming Interface (API). When you’re just starting out, it’s critical to figure out the difference between functions that are part of PHP and functions that are part of WordPress.

Here’s four functions you absolutely must know for effectively programming in WordPress. I suggest either memorizing these functions (smart) or have their definitions on speed dial (not as good, but it’s how I do it).

  • dirname: returns the directory path to the file given as argument. This is the directory on the server, not the URL path. PHP function.
  • basename: returns just the file name for a given path. Dual to dirname. PHP function.
  • add_action: adds a specified function to a WordPress action. Example: if you want to print your own meta tags into your web page head element, create a function and use add_action to tell WordPress where to print the output of your function. See Line 20 in Anchor Text Plugin.WordPress function.
  • add_filter: modifies text before printing that text to a WordPress page. For example, WordPress uses a filter to automatically add paragraph breaks to your blog posts. (Which some people really hate, but what can you do?). WordPress function.

Low Mercury from Groovera Chilled Web RadioBy the way, I just got a nice email from Tim Lumen, who operates Groovera.com. Curiously, I just happen to be listening to Low Mercury right at this very moment. Low Mercury is super-chill, great for those days when Trance, Techno and Breakbeats is just a little too much. If you’re in a kick back writing mode, check ‘em out. Groovera is 100% listener supported, and worth it. If you like what you hear, donate or subscribe. If you’re in budget mode, give Tim a little link love. Or both!

Related reading

Here’s some articles you might like from 2009:


*Make and cpp don’t count. La la la I can’t hear you. Never let facts interfere with a good story.

WordPress Widget Plugin – Super easy customization (Tuesday means technical)

(Reading time: 11 – 18 minutes)

We hear it all the time: speed of implementation. Execute fast. Fail fast, even. But all of this sterling advice assumes we know how to execute.

When you’re starting from scratch, with big ambitions, you have a problem: you can’t execute on any of your ideas.

There is a solution…

…when you can’t do what you want, do what you can.

For example, I want to build the Next Big Thing, but my network programming skills aren’t up to scratch. I could choose to be in a bind and do nothing, or I could choose to build the necessary skill set.

It’s building the skill set for me.

Note: in the software business, and especially within the startup ecosystem, business acumen and programming wizardry are not assumed to be mutually exclusive. In fact, a lot of the real rock stars in Silicon Valley are better than average at both.

As it turns out, I was chatting with Jenn Jinright about this very problem, this skill building problem. She’s relatively new, and has just started to realize the stupendiosity of the amount of work involved in building any business, much less a business based on the internet subject to global labor pressure.

I told her I was in the same boat, in a different area, and that I would finish up an article to demonstrate how I do it.

This is that article.

Design top down, build bottom up

The strategy is to fix a general picture of what you’re aiming for, then figure out what the pieces of that puzzle look like. You won’t see it clearly. That’s ok. This is top down design.

Once you have a general notion of what the pieces look like, build those pieces, which is easier said than done. This is building from the bottom up.

You may (will) end up building things you don’t need. That’s how it is. The things you do build may not (won’t) work the way you think. But if you keep after it, you will build yourself a toolchest, an arsenal of weaponry which you can haul out to solve tactical problems as they come up.

Because this is Technical Tuesday and because I’m building a suite of WordPress plugins for various reasons, I’m going to use WordPress plugin development as my motivating example. I’d be delighted to write another article on this topic using, say, an AWeber list segmentation to deal with a technical upgrade to an information product (Thesis theme customization). Just let me know.

Note: If you’re a DIY’er (and a lot of you are), you don’t need to understand exactly what’s going on in the code example below. But if you follow along, you will learn a great technique for teaching yourself.

6 reasons for Technical Tuesday

Most of my articles on Website In A Weekend solve several problems at once, but just to be clear, here’s my motivation for these “technical tuesdays”:

  1. Building out a plugin toolset for fast execution. With a little care, plugins can be designed to snap together like Legos. I leveraged a couple of existing plugins this way to build the Statustar demo at the last Bay Area Startup Weekend.
  2. Search engine bait for WordPress widget development, on a topic not well covered. This means I didn’t find any code that worked the way I wanted, out-of-the-box, so I write my own code and article.
  3. My content strategy reserves one day a week for deep tech, the hard stuff, The Hero Stuff. Long time readers (bofem) know this.
  4. I write to learn. I teach this stuff to myself. You can learn right along with me, and what I do here is an excellent way to teach yourself.
  5. Deliberate practice forces learning. It turns out the difference between “good” and “great” is doing the work that matters. Building technical skill very fast matters to me. Once a week I do that work.
  6. Last, and far from least, this is part of the base code I used to create the Blog Post Engineering Affiliate Widget plugin. No messy text boxes in my sidebar. More about that at the end, including how you can get the plugin yourself.

This still begs the question…

Why use plugins at all, if they’re so slow?

Here’s the deal: instead of fooling around with functions.php or custom_functions.php, write a little plugin instead. Theme files aren’t portable, plugins are. If you break your theme, that’s a major malfunction. Breaking an accessory plugin, no big deal, just delete it.

Warning: Informed Opinion Ahead.

Before we go any further, I’m just sure someone is thinking “Too many plugins makes WordPress slow!!!”

Yes and no.

How WordPress plugins affect loading speed depends on not just the extra HTTP requests, but also on:

  1. What those plugins are doing, that is, what functions they use in WordPress.
  2. How many files are packaged with the plugin.
  3. How many lines of code in the plugin are executed.

It turns out it’s pretty hard to predict performance in advance, which is why we have (surprise) performance testing. I’m not aware of anyone who has published performance results accounting for any of these plugin dependencies. Hopefully, somebody smart will latch on to this notion and do some quantitative testing. Or pay me to do some quantitative testing, that would be fine too.

We’re going to look at code now. If this is a problem, jump the code.

WordPress Widget Demo Plugin

Here’s the whole listing, it’s pretty short, you can cut and paste it if you want but I would recommend typing it all in by hand. You will learn it better that way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
/*
 * Plugin name: Demo Plugin Widget
 * Plugin URI: http://website-in-a-weekend.net/plugins/demo-plugins/
 * Description: Demonstrating how to add a WordPress widget with a plugin.
 * Version: 0.1
 * Author: Dave Doolin
 * Author URI: http://website-in-a-weekend.net/
 */
 
if (!class_exists("demo_plugin_widget")) {
 
	class demo_plugin_widget extends WP_Widget {
 
		function demo_plugin_widget() {
			$widget_ops = array('classname' => 'demo_plugin_widget', 'description' => 'A Widget Demo' );
			$this->WP_Widget('demo_widget', 'Plugin Demo Widget', $widget_ops);
		}
 
		/* This is the code that gets displayed on the UI side,
		 * what readers see.
		 */
		function widget($args, $instance) {
			extract($args, EXTR_SKIP);
			echo $before_widget;
			$title = empty($instance['title']) ? '&nbsp;' : apply_filters('widget_title', $instance['title']);
 
			if (!empty($title)) { 
				echo $before_title . $title . $after_title; 
			}
			?>
 
<ul>
	<li>Some text here.</li>
	<li>More text.</li>
</ul>
 
<?php
            echo $after_widget;
		}
 
		function update($new_instance, $old_instance) {
			$instance = $old_instance;
			$instance['title'] = strip_tags($new_instance['title']);
			return $instance;
		}
 
		/* Back end, the interface shown in Appearance -> Widgets
		 * administration interface.
		 */
		function form($instance) {
			$instance = wp_parse_args( (array) $instance, array( 'title' => '', 'entry_title' => '', 'comments_title' => '' ) );
			$title = strip_tags($instance['title']);
			?>
 
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title: 
    <input
	   class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
	   name="<?php echo $this->get_field_name('title'); ?>" type="text"
	   value="<?php echo attribute_escape($title); ?>" 
	/>
</label>
</p>
 
			<?php
		}			
	}
 
	function demo_widget_init() {
		register_widget('demo_plugin_widget');
	}
	add_action('widgets_init', 'demo_widget_init');
 
}
 
$wpdpd = new demo_plugin_widget();
 
?>

A few dozen lines of code gets a simple widget. This is very cool, seriously cool.

Break it down!

Now we’re going to explain how the widget code works by breaking it down piecewise. If this is a problem, jump the code explanation.

Let the learning begin: I’m using Safari browser on my Macbook, and I’ll be using Google to look up a few references I’m not sure about. We’ll figure out what is going on, and why.

11
12
13
14
15
16
17
18
if (!class_exists("demo_plugin_widget")) {
 
	class demo_plugin_widget extends WP_Widget {
 
		function demo_plugin_widget() {
			$widget_ops = array('classname' => 'demo_plugin_widget', 'description' => 'A Widget Demo' );
			$this->WP_Widget('demo_widget', 'Plugin Demo Widget', $widget_ops);
		}

The easy stuff:

  • Line 11: ensure there isn’t any conflict with existing code. This may seem faintly ridiculous, and in production (shipping) code, maybe it is (maybe it isn’t… I’ve had collisions with my recipe plugin in the past). When you’re developing, these kinds of conflicts can occur as a side effect from using advanced development techniques such as “cut-n-paste.”
  • Line 13 opens the class definition. We’ll close the class definition on line 75.
  • Line 16: The widget needs to know about itself, and it needs to be able to tell you about itself.
  • Line 17: Set the WP_Widget base class parameters 1. the ID used for targeting, css, etc., 2. descriptive text to display in the title bar in the Widgets interface, and 3. our class array.

Standard stuff, really, once you see it a few times.

Next, we need to override the three required functions of WP_Widget: widget, update and form.

23
24
25
26
		function widget($args, $instance) {
			extract($args, EXTR_SKIP);
			echo $before_widget;
			$title = empty($instance['title']) ? '&nbsp;' : apply_filters('widget_title', $instance['title']);
  • Line 23: widget is a required function, you have to override it.
  • Line 24: grab the variables we need, but (EXTR_SKIP) don’t overwrite any variable we already have.
  • Line 25: $before_widget is a variable obtained from the sidebar. It might contain some HTML markup controlling the layout of the widget in the sidebar. For example, check out this WordPress custom sidebar example. This is really interesting code design, the layout is manually controlled within the widget. I would not have done it this way (too easy to forget), and I’m curious what the design tradeoffs are.
  • Line 26: If the title variable is empty, give it a single space (&nbsp) to help the layout render when it’s displayed. Else set the title.

Moving right along…

28
29
30
31
32
33
34
35
36
37
38
39
40
			if (!empty($title)) { 
				echo $before_title . $title . $after_title; 
			}
			?>
 
<ul>
	<li>Some text here.</li>
	<li>More text.</li>
</ul>
 
<?php
            echo $after_widget;
		}

It’s getting easier, sort of…

  • Line 28: Not a big fan of double negatives. I’m not the brightest bulb in the building, so I always have to pause for a moment with “not empty.” I’d prefer something like “full.” Heresy.
  • Line 31: We need to jump out of PHP and write some HTML directly.
  • Lines 33-36: Dummy text, instructional purposes only.
  • Line 38: Get back into PHP, more work to do.
42
43
44
45
46
		function update($new_instance, $old_instance) {
			$instance = $old_instance;
			$instance['title'] = strip_tags($new_instance['title']);
			return $instance;
		}

This is easy, the update function handles everything that happens when you set the values in the widget when your in the Appearance -> Widgets administration area.

Form is also easy, it lays out the HTML you use in the administration area:

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
		function form($instance) {
			$instance = wp_parse_args( (array) $instance, array( 'title' => '' ));
			$title = strip_tags($instance['title']);
			?>
 
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title: 
    <input
	   class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
	   name="<?php echo $this->get_field_name('title'); ?>" type="text"
	   value="<?php echo attribute_escape($title); ?>" 
	/>
</label>
</p>
 
			<?php
		}			
	}

Long snippet here. No matter, we’ll take it a line at a time.

  • Line 52: $instance is where the current data lives. If we change that data, the changes are handled in update.
  • Line 53: Strip tags gets rid of HTML, Javascript and other potentially nasty artifacts, increasing the security of your code.
  • Lines 56-64: This is the HTML code shown in the actual widget itself. In this case, “Title:” labels an input element which sets title variable.

Not so bad.

70
71
72
73
74
75
76
77
	function demo_widget_init() {
		register_widget('demo_plugin_widget');
	}
	add_action('widgets_init', 'demo_widget_init');
 
}
 
$wpdpd = new demo_plugin_widget();

Almost done:

  • Line 73 adds our custom widget to the list of widgets WordPress already knows about, using the function defined in line 70 as the relevant callback. You probably already know this, I’m just writing it out to be complete.
  • Line 75 closes the class definition.
  • Line 77 is important, it initializes an instant of the widget. If you used this widget in your own plugin, you might want to initialize it somewhere else, perhaps in the main plugin class.

And that’s the end of that.

Get a grip on this simple code, and you will be able to snap a widget into your own code very easily. Not quite cut and paste, but very close.

Using the widget plugin

Having developed this widget component for Startup Weekend, it was only natural to snap it into the the Blog Post Engineering Affiliate plugin.

It’s really cool. You just download the bpe.zip file to your desktop, upload it using the WordPress plugin installation panel, and configure your sidebar with your affiliate link. No more messing around with text widgets and URLs.

Having the widget code “in my back pocket” let me build the affiliate plugin really fast. It took about 45 minutes to implement the widget, and part of that was an error on my part. Using it will save you a LOT of time.

So, are plugins slow or not?

As mentioned in my estimated reading time plugin article, having more plugins goes counter to received opinion in Blogistan (i.e., more plugins is bad.)

Recall I said something about taking anyone’s opinion on this with a grain of salt. Because until you measure performance, it is simply opinion. I guarantee 99% of the people that spout this nonsense haven’t ever fired up YSlow and checked to see which plugin is the slowest. Last I checked, it was Tweetmeme here on Website In A Weekend. It’s going to be different on your WordPress installation.

Here’s how the expert opinion works: if you have very little experience, and you ask someone with a lot of experience… they’re going to tell you something you can understand and act on: “Remove your plugins to speed up WordPress.” (If they don’t tell you to Read The Effen Manual instead.)

Easy. Useless. I like my plugins. All of them.

They aren’t likely to tell you “Install Firebug and YSlow, then run a few performance tests to average plugin load time to see which plugins are slowing you down.” (Actually, they might if you paid them real money.)

Don’t take my word for it. Think for yourself. Test it for yourself.