Need a WordPress website this weekend? Start here...

Technical Tuesday: Another Look at WordPress register_activation_hook

(Reading time: 7 – 11 minutes)

Wait! Stop!

There’s much more here than source code. You can skip right over the register_activation_hook example code. Unless you’re desperately seeking solutions, then you want to read every word.

Still with me? Cool. Let’s get started.

Technical documentation is hard to read and harder to write. As a programmer, you aren’t rewarded for writing documentation, no matter what management says, so documentation tends to be lean, spare.

As a reader, you know you’re putting on the turswiry hat before you even crack open the manual.

When you finally break out the manual, you’re invariably faced with learning about how complicated it all is. Then,

Once you figure it out on your own, you can’t say the man pages don’t say that. – Jason Cox.

Wisdom from East Tennessee indeed.

It’s that “figure it out on your own” part that’s so hard. It takes a lot of practice, both to do the figuring, and knowing when you need to take the time to do the figuring.

Because it is time consuming.

Here’s my practice “figuring it out” for today.

(Non-programmers, skip past the code).

Example code from WordPress.org forum

WordPress is a large and rich application. It’s fairly well written; I’ve seen far worse code. And it’s fairly well-documented.

But there are still a lot of dusty corners. One of these is the register_activation_hook function. Most plugins need to use, but there’s not a lot of accurate discussion about exactly how to use it.

I was poking around for some example code, and ran across this snippet posted by Gleb Esman. Gleb seems pretty cool, he’s the author of the MemberWing plugin and service. But he didn’t get this one right, and I’m going to show you why. Let’s take a look:

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
<?php
/*
Plugin Name: A Test
Description: A Test
*/
 
require_once (dirname(__FILE__) . '/my_other_file.php');
 
// This code *will not* work. Activation hook function must be defined in the main plugin file.
//register_activation_hook (dirname(__FILE__) . '/my_other_file.php', 'my_other_function');
 
//(Dave) But this code works just fine! 
register_activation_hook (dirname(__FILE__) . '/activation1.php', 'my_other_function');
register_deactivation_hook (dirname(__FILE__) . '/activation1.php', 'clean_em_up');
 
// This code will work.
//register_activation_hook (__FILE__, 'test_activated');
 
// This is correct way to declare/access globals.
global $some_var;    // globals must be declared explicitly. Without this you will not be able to access '$some_var' from within 'test_activated()' function.
$some_var = 'hey';
 
//===========================================================================
function test_activated ()
{
   global $some_var; // Now it will be 'hey'.
 
   // This function is defined in 'my_other_file.php'
   my_other_function ();
 
   // This will not work, so don't try. If you need logging write something in temporary log file in here via fopen/fwrite.
	// If you want to quickly test if your activation hook works - put exit() into it. At least you'll see error during activation.
   echo 'test_activated called!';
}
//===========================================================================
?>

First, please accept my apologies for the misaligned line numbers. This is a Thesis CSS issue, the table layout design between Thesis and the plugin doesn’t work very well. But it’s still workable. Let’s walk through it line-by-line:

  • Line 3: the plugin name. Critical. We’ll return to this later.
  • Line 7: I’ve listed this file below as well, we’ll look at it line by line next.
  • Line 10: Doesn’t work, true, but the explanation is wrong.

    Fact: WordPress will register any callback in scope.

    The problem here is that activation hook operates on the plugin name. The name of the file (line 10) containing the callback is irrelevant.

  • Line 13: Registering the callback with the correct filename works.
  • Line 13: (Bonus) register_deactivation_hook works too.

I’ve left the rest of the code in place so that you can compare my additions linewise with the original register_activation_hook example.

Callbacks in different file

Now we need to take a look at the code in my_other_file.php. Having these functions in a different file is irrelevant for a plugin this small, but it does serve a useful purpose for testing. For larger applications, separating important parts of the code is an important principle of software design.

1
2
3
4
5
6
7
8
9
10
11
<?php
/* Callback for activation hook */
function my_other_function() {
	add_option('activation1','Activated');
}
 
/* Callback for deactivation hook */
function clean_em_up() {
	delete_option('activation1');
}
?>

This is easy stuff, the callbacks just add or remove an option in the WordPress options table.

When you run the code presented in these two listings, take a look at your options database, as shown in this screenshot:

register_activation_hook test using options database

register_activation_hook test using options database


There’s other ways to check, but this is pretty fast, and if you aren’t familiar with the options table you need to be.

Why is register_activation_hook so hard?

I can’t speak for everyone, but here’s what I think:

  • PHP variable scoping rules feel kooky coming from a C/C++/Java background. PHP looks like C, smells like C, but doesn’t really walk like C. Trouble comes when programmers absent-mindedly crank out PHP code, unaware of the differences in scoping rules.
  • Callbacks give people trouble, even these activation/deactivation functions which are so simple they don’t even take arguments.
  • Man pages are inaccessibly written, and often out of date. But manual should be the first place to start. If the manual has test code, run it to check it’s accuracy.
  • Even fewer people read the code. The comments for register_activation_hook are crystal clear about what’s expected. If only people would read the source!

You should probably jump over to Reverse Engineering Activation Hook In WordPress Plugin API for more information. This is not really a series of articles… yet. Although I do have at least a couple more articles to write on register_activation_hook. Maybe three or four more. At the end of the last article (that is, when I get tired of writing them), I’ll give you a two-step procedure ensuring you will never, ever have trouble with this function again.


Ok, enough preaching… here’s something for you scanners…

What’s in it for me?

More work, if you’re so inclined. But this is good work. Your work.

Here’s the deal. My friend Deacon and I have a long running discussion on deliberate practice. We both crave personal and professional excellence, and we believe that the path to mastery is in the practice of mastery. Deacon cuts wood blocks. I cut code.

masteryPart of our inspiration comes from this little book, George Leonard’s Mastery. In about 100 small pages, Leonard lays out how mastery is achieved through practice. Practice in the sense of “doing what you do” on a regular basis, with deep concentration.

Practice puts the journey first.

The means become the ends.

Here, taking on some silly misconceptions about some random WordPress function is not what’s important.

Instead, the process of examining the problem, understanding why the problem exists, and constructing an elegant solution is my path to mastery.

I don’t care about register_activation_hook. I care about:

  1. Understanding WordPress coding conventions. Understanding this code helps me “get inside the developer’s heads.” I want to think how they think. That’s when the “programming” ends… and the creativity begins.
  2. Learning PHP behavior, specifically, variable scoping rules. Same as above: practice the programming so I don’t have to think about it.
  3. Ensuring my plugins work correctly when I need to invoke the activation hook. I have a legitimate need to understand how this function works.
  4. And… (long time readers know what’s coming) smacking down an under-served keyword. Actually, two. An hour of free blog post engineering to the first person who guesses my second keyword.

Learning the intricacies of register_activation_hook is just the convenient vehicle carrying me further along my path.

What’s your path to mastery?

Do you have a regular practice? If so, tell us about it!

Carlos Throws Down, and Closed Means Closed. Yep, the Week in Review

(Reading time: 6 – 10 minutes)

You know those people who, once they succeed at something, turn right around and start succeeding at something else? Or that person who so elegantly spins a score of plates, never dropping one? Or those two people that can’t stand each other, until they finally meet each other? Let’s meet them all, right here, right now.

But first things first: Drivel Alert! The following has f***all to do with building a Website In A Weekend. If you have drivel issues, might want to pass on this one!

Bird’s custard powder

I was hanging out on twitter earlier, wondering what to write for this Week in Review, so I decided to just ask. Up pops Kelly Diels with a link to a story about appearance and connection from Bindu Wiles.

This story connected with me in two ways. First, I learned about Bird’s Custard Powder. I’m a guy, and food is important to me. Especially really cool food like custard what comes in a can. Visions of camping trips, Burning Man and the like swim through my imagination.

Second, Bindu’s connection is face to face with her neighbor… but the web allows so many more people to connect with her. How many of us carry around dumb little feuds? And who can we really talk to about them? Friends and family get tired of hearing about it (“Why don’t you just move if you don’t like your neighbors?”) But on the web, we find ways to connect and share such experiences.

On the web, we’re exposed to ourselves through other people’s experience.

Safely.

Yet immediately. Bindu is real. You can leave a comment on her web page. You can talk with Bindu on Twitter.

My point is this: Relationships on the web aren’t better or worse than relationships in meatspace. They’re just different. We’re free to use the web to cheapen our relationships, or to deepen them. The web is just a bunch of wires and waves, it doesn’t care. We define the meaning.

You have how many websites, again?

Then Ricky Buchanan issues a blanket invitation “pick on me any time you like.” Why, Ricky, I think I will!

Ricky is amazing. She runs a half dozen websites, and runs them well. I can barely run Website In A Weekend, and that’s after neglecting several other websites. I won’t list all of her sites here right now, but I’ll work my way through them over the next few weeks.

For now, take a look at Atmac.org: Assistive Technology for Apple and Mac Users. Ricky is a bona fide expert with assistive technology, and an extremely competent web designer.

Poke around a bit. Meet Ricky. I’ll pick on her more in a week or two, we’ll take a look at some of her other websites.

Carlos Velez throwing down

Recall Carlos wrote a couple of very well received articles (Pre-writing Part 1, Pre-writing Part 2) describing his method for making sure he has lots of articles ready to publish at a moments notice. He calls it “pre-writing.”

Now, I’ve written about “scheduling in advance,” which is the same damn thing, but that just doesn’t have the same ring as pre-writing.

In any case, Carlos smacked a couple of home runs, and like any true champion, he goes right back to work with this:
Carlos Velez Prewriting challenge

I suspect Carlos has an unfair advantage. He’s friends with this Aaron Pogue dude, who, evidently, knows a little bit about writing. Aaron’s on my radar screen now… we’ll expose this nefarious conspiracy once the sordid details emerge.

I sell stuff

It’s true. And it’s even worse: I like selling stuff.

I sell my stuff. Last week I sold 11 copies of my magnum opus
an ebook on publishing blog posts I’ve been working on for a few months. Now, I’ve sold a grand total of 20 copies, and that’s all I’m selling at this version (0.5). I’m getting great feedback from early buyers, which I’m using to improve the ebook for the next version (0.7).

For reason I’ll divulge later, I’m planning on selling no more than 30 of the 0.7 version a few weeks from now.

I suspect these will go pretty fast.

Why am I telling you this?

Because when I’m done selling those 30 copies of version 0.7, I won’t be selling any more of that version. “Doors” aren’t going to “reopen,” there won’t be a “waiting list,” I won’t subject you or anyone else to the mailing list browbeating experienced by Mike CJ.

Of course, I’d like to sell about a million ebooks once I’m finished with version 1.0, but that’s a ways off. And you’re perfectly welcome to wait.

In any case, if you think you might like to learn a systematic way to handle “publishing” chores, check out what people are saying, then either sign up for the newsletter (sidebar), or follow along here on the blog. I’ll announce it in both places, but in the newsletter first next time.

I sell other people’s stuff too. In fact, yesterday I sold a copy of Digging into WordPress, an excellent ebook published by Perishable Press. It’s hundreds of pages of hard core, technically accurate WordPress knowledge. I’d like to sell a bunch more of these. The authors, Jeff Starr and Alex Coyier, really know WordPress inside out, and they’re good writers too. I picked up my copy instantly, as soon as they released it.

If you spend any time at all rooting around in WordPress code, Digging into WordPress will save you time. Probably a lot of time.

I’m also a member of the Third Tribe group, and will be proud to offer my affiliate link once their system is set up. Third Tribe is doing something a little different: you can’t be an affiliate unless you are a member. I’m a member, and I recommend that if you’re serious about your internet-based business, you join as well. Stay tuned for a link.

By the way, if you’re a long time lurker here and wonder why I link to some of the same people over and over and over again… it’s because they don’t lurk. I can’t link to you if I don’t know who you are!

New articles

The Week In Review Series

Last WIAW Week in Review
Caressing Alien Species, and, a (late) Valentine… Take cover! It’s two Weeks in Review. We’re catching up after a botnet attack. Some good stuff in here: late Valentine, art, some guitar pr0n. Check it out!

Next WIAW Week in Review

Stay tuned…