Blog

Add a Repeating Text Field to Options Framework Plugin

July 18, 2013
Options framework repeating field

Options framework repeating field

This is what we’ll be building.

I don’t hardly even know why I was working on this today.  Well a friend wanted to be able to control the radio buttons in a metabox, from the backend (since the otherwise brilliant WP-Alchemy is all dev-level coding) and for some reason  my brain went to theme option.  He ultimately went a different route and used Advanced Custom Fields.  But some days I just feel like not working and doing something fun, and the question of repeating fields in the theme options piqued my interest.  I asked Devin Price if his awesome Options Framework plugin has such a thing and he replied that no it didn’t exist…. yet. He wasn’t sure it was possible, which is like the worst thing to say to me. Of course it is possible! And now instead of working on something responsible, I will now solve this riddle. So I started digging into Options Framework. At first I thought that I would fork OF, but it turns out that all the functions/filters needed are already in place!   Wherever you have your $options array in your theme’s options.php to get a repeating field you’d define your custom option like so:

Then to handle all the parts of displaying this, scripting the repeat, and validating the data you’ll need the following group of functions, added to your theme’s functions.php.

Creating the Output

First, we need to output something when Options Framework gets running and encounters the custom option of type ‘repeat_text’. Devin has a catch-all filter already built-in, so we just have to attach a function to the {$option_type}_option_type filter, in this case repeat_text_option_type. This callback will create the input box (as many as needed by the array of values) plus one hidden one. It also creates the “Add New” button and for good fun we’ll throw in delete buttons next to each input. The markup (and later the script to handle the repeat) draws a lot of inspiration for WP Alchemy’s repeating groups.

Sanitation and Saving

Options Framework won’t save anything unless the data gets run through a sanitization filter. The neat thing, is that if you set up the input names as name="somefield[1]" and so on, WordPress will automatically save all the “somefield” fields in an array. So we just need to rifle through the array and sanitize each text field. We can do this quickly with array_map. Next

Style and Scripting the Repeating Fields

Finally, all the bells and whistles. What good is a repeating field if it doesn’t, you know, repeat. Again, I have to credit Dimas Begunoff for his WP Alchemy class. I’ve simplified some of what he was doing in metaboxes, by merely adding a data-rel to the hidden input. Then a few quick on handlers for the button click events and that hidden input we created earlier gets cloned and given a proper name attribute. Clicking a delete button, removes it’s associated input from the DOM.

Output

Because we’ve saved an array of data the if you try to echo out the results of of_get_option('example_repeat'); you will get Array. You have to loop through the array to print out each on individually with a foreach loop.

This is definitely beta-ish. For instance, I know it doesn’t take into account a way to set an array of defaults… like if you wanted to have two fields set up as the default. Maybe it is Google Chrome, but I’m also having a little issue with tab indexing. And finally… there was something else, but my mind just went blank. Get the full code from my Gist. As beta code, I am totally open to suggestions and improvements, but I won’t be able to help you set this up on your own sites. I’m just putting it out there for information purposes only. What would you use a repeating field for in theme options?

WordPress Filters Fundamentals

October 20, 2012

Ok, so you’ve read my previous articles on PHP basics and how to use WordPress action hooks. Now you want to play with the big boys and girls and try your hand at filters. Just a reminder that you are still essentially learning a new language. Be patient with yourself. It took me close to a year to really understand filters, so if I can help you learn it quicker than that I’ll consider this a successful article.

In my discussion of hooks and functions I have described the system of hooks in WordPress as being similar to a parking lot. The hooks are like spaces, the cars are like functions that can be parked anywhere and can be moved around. To expound on this metaphor, (or to beat it to death) I think a filter is similar to changing something about the car while leaving it in the same place. A filter is like a magic function box that takes a value in ( remember I talked about parameters in by Basics tutorial ) do something with it and send it back. So you have a red Porsche on the lot, send it to a filter and it might become a blue Porsche. Or a black pickup truck. Whatever. But it will still be parked in the back, 2 spots from the end.

When browsing WordPress core, themes and plugins, you will be alerted to the availability of a filter by the appearance of the apply_filters() function. In generic terms it will look like so:

It might look like:

or:

or even:

Parameters for the Filters

But I repeat, the big tip off is the apply_filters() function. The apply_filters() function can take an unlimited number of parameters but only the first two are required. 1. The first is the name of the filter. I was very confused early on because the Thematic framework tended to name the filters the same thing as the functions that contained them. And then in the one instance where they were different, I couldn’t get my filter to work for anything. I swore and threw things, cried and probably shaved a few days off my life from the stress. Turns out their sharing names was a convenience factor that makes a lot more sense to me now. So, just remember that first parameter is the filter’s name. 2. This is an important one, because this parameter is the variable that your function will receive. This is the value we’re going to change. This is the red car that we will turn blue. 3. This it the priority. Just like with adding functions to hooks, this controls the order that filter functions will be applied should there be more than one. The default is 10, so if you need your filter to run before that you’d use a lower number. This is rare, and usually you need to run your filters after others, so you’d want to use a higher number. In fact, until you are sure that you are conflicting with another function you can pretty much just leave it at 10. 4+. These are other variables that might give you some useful information for manipulating the variable getting filtered. Remember we talked about scope in the PHP Basics. Instead of declaring these globally and hoping they arrive intact, WordPress will send your filtered variable along with some friends.

A Filter with Training Wheels

In super generic terms let’s take a look at the basic set up for filtering.

The structure is almost exactly the same as that for add_action(). In reality, we are adding an action, just of a slightly different type: one that modifies a specific variable’s value. One thing to note here, is the number 2. This is the number of parameters that you are passing into the function. You’ll always pass 1 variable ( ie. the variable that you are filtering ) and in this case you wouldn’t even need to declare it. That’s the default value, just as 10 is the default value for #priority. However, some filters provide access to other variables (like our fake $other_arg), and if you want to use them in your filter function then you have to name them inside the parentheses and then write the correct number at the end of the add_filter() statement.

If you have 2 parameters in the function, but don’t have the number 2 at the end of add_filter() you will get White Screen of Death. If you have the number 2, but don’t declare two parameters, guess what, you will also get WSOD. So make sure your parameters match up. And you absolutely, must, sans doute, return a value. If you do not, that is essentially the same as returning a null string. If you echo something here, it will likely not appear where you expect it, so don’t. RETURN, RETURN, RETURN.

Remember in my PHP basics I talked about two functions playing catch. The return statement, is you throwing your modified version of the variable back to the apply_filters() function so that WordPress can continue on its merry way, but using your value now.

You’re a Real Boy Now, Pinocchio.

A Real Filter If you’ve managed to read all this, then… well… Bless you. I want to end on a real filter that you can drop into your theme’s functions.php and actually see a working result.

Not too shockingly I am using Bacon in my testing code. If this bothers you… well, its not real bacon and you may use whatever you wish in your own tests. WordPress has a filter called the_title() that lets you modify the title of every post! As written above it will literally add BACON everywhere the_title() is called. Bacon everywhere, all the time has its appeal, sure, but I will whet your appetite with some neato WordPress conditional logic that will only add Bacon to the titles in the main loop, and only on the front-end.

Conclusion

I hope that helps things make more sense. Remember, THIS IS HARD!! Do not be discouraged if you don’t get it right away. I cannot provide specific support in the comments ( Hire Me, instead! but do let me know if there are places where I could be more clear.

Nav Menu Roles Plugin

September 18, 2012

Over the weekend I was working on a project and my client needed to be able to hide certain menu links from non-logged in users.  In the past I have just created 2 menus, one for logged in users, and another for logged out users.  Not the most convenient thing ever, but simple enough.  However, since this was at least the second, and possibly the third time this has come up in various projects I decided to dig further.

Adding fields to the menu item back-end

This was the trickiest part really, because there aren’t any action hooks in this part of the code.  I have requested one with the following Trac Ticket, but until that gets added to we have to do it in a slightly less efficient way.

Thanks to this WordPress Answer I found that the whole menu item form is created by the Walker_Nav_Menu_Edit Walker, but that tucked away in the code is the ability to filter this and send a new Walker via the wp_edit_nav_menu_walker filter.  Actually this answer got me about 80% of the way there so I can hardly claim to be clever or original.  I just packaged it up.  Couples with this Answer about front-end menu Walkers, the first beta draft of my plugin was born.  At this point it really only handled different roles.

Nav Menu Roles screenshot

New options for menu settings allow you to customize who can view particular menu items

Before it was even added to the WordPress repository, Pippin Williamson did a quick video review, so I guess I am not the only person who has needed this ability from WordPress.  Pippin also had the cool idea to add the ability to show an item to all logged-in users, or all logged-out users, so the video screenshots will look different from the end result of version 1.0.  I think this was a cool addition, so thanks Pippin for the idea and for helping me work on it.

Basic Usage

Install and activate the plugin like normal. Create a custom menu and add items to it just like you usually would. You will now see the extra fields shown in the screenshot. From here you select to show the item to all logged in users, all logged out users… or to customize by role. If you chose customize by role, then you can use the checkboxes to determine which roles should be allowed to see this particular menu item. If you choose customize by role and do not check any roles, then the item will show to everyone just like it used to. There isn’t any more to it than that. It should be pretty straight-forward.

Download

Now available in the WordPress Repo.

Also available via my Github repo.

Support

Support is limited to bug-fixing and basic implementation. I can’t help with any customization.

Please report any bugs at Github’s issue tracker.  

Support requests are best handled in the Support Forums. Please don’t post support questions in the comments!

Enjoy! And let me know what you think.

Absolute PHP Basics for WordPress Newbs

August 3, 2012

“I’m just a designer. I’m comfortable with CSS but PHP scares me.” Yeah ok, well first off, if you are a designer…. instead of banging your head into a wall to learn a coding language, why not hire a developer? Some of my best clients have been designers. It is kind of a win, win. I get to work on pretty sites and you get to do more designing and less stressing. Send me an email and let’s see if I can help. But if you insist on trying to defy your right-brained designery nature and become more left-brained here are a couple of points that I think will help you as you try to learn both PHP and its sub-dialect of WordPress.

Function Function What’s Your Function

Functions do things. Ever learn about functions in middle school math class? Magic black-boxes where numbers go and come out as something else? Well it is pretty much the same. Let’s start with the simplest function possible, a nice spin off on the classic hello world().

But not all functions echo out a value because we don’t always want to echo (which is just another way to print something) a value out right away. Sometimes we need to process it more, etc. In that case you’d return a value. Returning a value is just the opposite of echoing a value. It says, don’t print it right now, save it for later.

To print it later we’d have to actually echo out the function.

or

See what we did there in that second one? We defined a variable, which if you’ll remember from math class is a bit of an amorphous blob that can have any value. Then we set that variable equal to the value returned from the hello_bacon() function.

Getting into Arguments

The hello_bacon() function is obviously super simple. It always returns the same thing. Well that’s not so much fun and sort of defeats the purpose of a function. Remember those magic black boxes? Well now we want to take a variable in, manipulate it and spit it back as something new and shiny. We send variables into functions as arguments to that function.

As you can see above, the favorite_food() function accepts 1 argument. Inside of the favorite_food() function this argument will be referred to by the variable $food. This sort of touches on a concept that we’ll get into in a bit, called variable scope. But for now remember that $food does not exist outside the favorite_food() function.

If you need to ensure that you never get an empty value for “My favorite food is ____” then you can give an argument a default. If you don’t pass an argument when calling a function it will simply use the default. Note below that ‘bacon’ is the default value of the $food variable.

By now you might have noticed that we’ve only been dealing with what are called, ‘string’ variable types…. words or letters essentially. You’ve been seeing me combine strings together with a period (.) in what is called string concatenation. But just like math class, PHP functions work on numbers.

Variable Scope

Whoa hold up! You just said the argument was called $x, but there you go calling it $a. Yup. Remember when I said it was important to remember that variables (usually) only exist inside the function where they are defined. That is what is called variable scope. In PHP and WordPress you can declare variables as global in scope, meaning $x has the same value everywhere, but by default variables are local in scope, meaning again, they only exist within the functions using them. I could rewrite the above to be:

I can call the variables anything I want, because the $guacamole in the double_it() function is not the same as the $bacon outside of it. Remember variables are placeholders. Think of it like the two are playing catch. In the following line:

We are passing a value to the double_it() function. The function then catches the value as its argument.

Now the variable has a new name, but the same value. In the example the value was 10, that part isn’t any different. Within the function the variable $guacamole now has a value of 10. Then it performs its multiplication and sends back the doubled value. The is the pass back.

And that brings us back to:

where the variable $bacon catches the return pass, and the variable $bacon is now equal to 20, which we see when we echo $bacon. So it is like playing catch. If you are out in the yard playing catch with someone who doesn’t speak the same language as you and you toss the ball to your partner, when she catches it, she might call it a beisbol. When she throws it back to you, it is a baseball again, you both just had different words (variables) for it. This is the official PHP manual that might help explain things if my metaphors made it clear as mud. http://php.net/manual/en/language.variables.scope.php

In Summary

We covered functions, function arguments, string variables, numeric variables and variable scope. There is quite a bit more, but I already feel like this is a lot actually and hopefully you are well on your way to programming hell… I mean bliss. Please point out any errors or places where I could be more clear, but keep Thematic and WordPress specific questions for their respective forums. Best of luck.

Radio Buttons for Taxonomies

July 12, 2012
Radio Buttons for Taxonomies!

Radio Buttons for Taxonomies! Unfortunately the subject can no longer be both guacamole and bacon. You’ll have to chose.

Every now and then I run across a client who needs a taxonomy where the user is restricted to only allowing one term per post.  I’ve also seen people wanting this a few times for categories, and I, myself, have wished for it a few times.  Sometimes a post needs to be like a piece of paper in a folder… and only be in 1 dang folder at a time.  Some might argue that categorization with a single, exclusive term is more-suited to post meta, and they might be right, but the ability to list all the existing terms is lacking from a post meta implementation.

So, the problem is checkboxes… checkboxes let users check more than one box.  So, the solution is then radio buttons!  Which enforce a single selection.  There are a few tutorials floating around on the interwebs on how to do this.

Hands-down, the best tutorial on radio buttons with taxonomies was written by Stephen Harris, so I owe him a huge debt for providing most of the guts of my plugin.  His OOP class implementation allowed you to define some variables, such as taxonomy and post type… and the class would do the rest, but only for a single taxonomy.  Well the whole point of OOP-style programming is that you can re-use it!  I set about building a standard plugin container with a settings page where you can check which taxonomies you’d like to convert to radio buttons.  I would then create a new object based on each of these taxonomies.  So I had to tweak Stephen’s class so that I could use it to create new objects (basically just switched his load method to __contruct() and pass those objects a parameter, namely the taxonomy.  I scrapped the other parameters.   The div id will just be standardized based on the taxonomy and the metabox will be changed for every post type that uses a particular taxonomy.

Radio Buttons for Taxonomies settings configuration

Now it is super simple to convert any taxonomy to radio buttons

Installation Instructions

  1. Install Plugin
  2. Activate Plugin
  3. Go to Settings>Radio Buttons for Taxonomies
  4. Check which taxonomies you’d like to convert to taxonomies and click Save Changes

Literally, that’s it.  And now when you return to your edit your post you will see the new metabox.  Hope you enjoy!  I have a few ideas for improvements, such as better error handling when you try to add new terms and getting radio buttons in the quick edit, but this should get you started.

Download

Download from the official WordPress Directory

or you can track, contribute to the development, or fork me at at Github.

A Newbie’s Guide to WordPress Hooks and Functions

July 10, 2012

When people start wanting to customize WordPress, specifically a theme like Thematic, or a plugin like WooCommerce, I always see questions like:

How do I add “something”, “somewhere”?

or

How do I remove “something” from “somewhere”?

or

How do I change “something”?

At first it is easy to think that adding a div to the #header is different from adding a menu to the #footer, but once you understand how filters and action hooks work, you’ll see these questions really all follow the same pattern. You just need to learn how to speak WordPress! Be patient with yourself, because you literally are learning a new language… especially if you aren’t already familiar with PHP.  I’ll be using examples for working with the [theme-link] but you don’t understanding hooks and functions and eventually filters will be handy in any WordPress project.  Let’s start…

What the heck is an Action Hook

Action hooks look like this:

do_action('this_is_the_action_hook_name');

In a plugin such as WooCommerce, if you investigate in the templates folder you will find all sorts of action hooks. The WooCommerce templates are extremely well-documented and tell you right there which functions are hooked into that action hook and in what order. In the theme, Thematic most of these are buried in the library/extensions folder.  In fact, in the actual templates (like index.php, category.php etc) you will see hooks that look more like:

// action hook for placing content above the index loop
thematic_above_indexloop();

But if you go searching for the definition of that function you will find that it is in content-extensions.php

/**
 * Register action hook: thematic_above_indexloop
 *
 * Located in index.php
 * Just before the loop
 */
function thematic_above_indexloop() {
  do_action('thematic_above_indexloop');
} // end thematic_above_indexloop

Now an action hook is sort of like a parking spot. Some are empty, some have cars on them. you can move the cars around, but the spots themselves stay put. When wordpress gets to an action hook, it will run all the functions that are attached to that particular hook. If it gets to a parking spot and finds a car, it will run that car. If not, then it will continue on to the next hook/space.

How To Add Any Function to any Hook

A completely fictitious example:

function function_you_want_to_add(){
echo "I heart bacon!";
}
add_action('destination_hook','function_you_want_to_add', $priority, $args );

The add_action line is doing the heavy lifting here, and always takes this same “form”…. it sort of reads like this in english:

Add the function called ‘function_you_want_to_add’ to the hook called ‘destination_hook’ in the order of $priority with some optional extra arguments called $args.

You can read all about add_action in the WordPress Codex (hint: there is a TON of info there, but I understand it can be overwhelming at first).

The $priority is always a number. It is like a traffic cop in the parking lot, or maybe just an orange cone. if more than 1 function wants to be on a particular hook the priority decides which goes first. If 2 cars wanted to be in the same spot, the one with the lower number priority would get ground level parking and the one with the higher priority would be stacked on top. Yay 3-d parking! Sorry, prepare yourself we are going to beat this metaphor to death. The default priority is 10, so if you don’t need to change that you don’t even need to define it in your add_action line.

Some hooks pass additional variables to the functions that operate on them, but this is pretty advanced so for an introductory primer we will ignore it.

Now, a practical example:

function function_you_want_to_add(){
echo "I heart bacon!";
}
add_action('thematic_above_indexloop','function_you_want_to_add');

If you add the practice example to your child theme’s functions.php you will see “I heart bacon!” appear on your blog page. Now leave that there and add the following just underneath it in your functions.php.

function kia_another_function(){
echo "Guacamole makes me happy!“;
}
add_action('thematic_above_indexloop','kia_another_function', 5);

Notice the priority number is 5. This means it has a lower priority number than the first function, which is 10 by default since we didn’t specify anything. When you reload your theme you should now see Guacamole makes me happy! on the blog index above the line about loving bacon. Bacon and guacamole together. It must be code heaven.

How to Remove Something From a Hook

removing stuff works a bit differently:

function remove_stuff(){
remove_action('hook_location','function_you_want_to_remove',$priority );
}
add_action('init','remove_stuff');

In english this sort of translates to:

When WordPress runs the init hook, please remove the function called “function_you_want_to_remove” that is located on the hook called “hook_location” with a priority of $priority.

init is just a WordPress hook. in fact, it is the one of the earliest hooks that run when WP starts whirring… it is like priority parking. You can see most all of the hooks that run in the WordPress process again at the Codex: Action Hooks  To remove something that had a specific priority originally, you must remove_action it with the same priority.  A good practical example would be removing the Thematic blog title.

function remove_thematic_header(){
remove_action('thematic_header','thematic_blogtitle', 3);
}
add_action('init','remove_thematic_header');

Paste the above into your functions.php, reload your child theme and poof the blog title is gonzo!

Moving the #access menu is another practical example, that combines adding and removing functions.  I’ll include it here because I see this question asked all the time.

function remove_thematic_header(){
remove_action('thematic_header','thematic_access', 9);
}
add_action('init','remove_thematic_header');
add_action('thematic_aboveheader','thematic_access');

Note that we don’t have to define thematic_access, because it already is defined by thematic. We can simply add_action it to a new parking spot.

Overrides R’ Us

Thematic has a bunch of functions built in that if you define them, they automagically replace the function thematic was going to add to a specific hook, with your custom function.  In WordPress parlance, this is called a pluggable function.  Many thematic functions can be overridden by copying a thematic function to your functions.php and altering the function’s prefix from thematic_ to childtheme_override_.  The overrides completely change the car that is parked on a particular parking spot but they don’t change its location.

For instance to override the thematic_blog_description you could put the following in your functions.php

function childtheme_override_blogdescription(){
echo "Evil laugh! Now your blog is only about bacon!";
}

Refresh your theme and you will see the blog description has been taken over by bacon. , which I think is neat.  Note that with pluggable functions you do not need to also call add_action.  Doing so will add the function twice.  Most functions in thematic have this override capability, but not all.  You can browse through the extensions folder (look but don’t touch the parent theme!)

If you see something like:

if ( function_exists('childtheme_override_blogdescription') )

That’s a sign that you can use the override feature.  The full IF statement reads something like:

If you define a child_theme_override function then Thematic will add your custom function to the appropriate hook instead of its own function.

Overrides are significantly more intuitive than filters, but filters can be more elegant: the scalpel instead of a broadsword if you don’t need to change the entire function.  However, this post is crazy long, so I will leave filters for the next part of series.

Additional Resources

To help you know what hooks are available in Thematic, here are 2 visual aids:

http://www.bluemandala.com/thematic/thematic-structure.html

http://visualizing.thematic4you.com

Additional Help

I’ve tried to make this as beginner-friendly as possible, but I’ve been doing this for a few years now and so it makes total sense to me. Please let me know in the comments if something about this tutorial is not clear so that I can make it better.

Also, I don’t have time to respond to specific support requests in the comments. If you have Thematic questions post them at the Thematic Forums or contact me for some premium support.

KIA Subtitle

July 2, 2012

now our subtitle input is always in the right place

Recently I was working on a project and needed a subtitle. There are probably two subtitle plugins already in existence. I happened to pick The Subtitle by Luc Princen, which worked pretty much as intended except the actually input box wasn’t always where it was supposed to be and I found that admin notices seemed to make it pretty unreadable and not totally obvious to my clients.

Well instead of seeing if this problem was solved in the other, already-available plugin, I did what I always do when I have more important things I could be working on: I fixed it. I went ahead and tweaked a bunch of other things too: like moving the plugin into a class (I have no idea if this is beneficial, but I feel smart doing it so I do), not saving “Subtitle” as the meta on posts with no subtitle instead of relying on the callbacks to not display it.  Making it translation-ready… with a whopping 1 translatable string.  Oh and just because I am all multi-lingual like that (meaning I can use translate.google.com) I translated it into french and spanish.

USAGE

Usage is covered in the readme.txt but I’ll cover it again here.  Wherever you want to echo the subtitle, you’d use the the_subtitle() template tag.  We’re wrapping it in the function_exists wrapper in case you decide to uninstall the plugin (why?), this way your theme won’t break.

[php]

if(function_exists(‘the_subtitle’)) the_subtitle();

[/php]

As of version 1.2, the_subtitle() accepts three parameters: a string to come before the subtitle, a string to come after the subtitle, and whether or not to echo the subtitle: true by default. Basically we are mimicking the capabilities of WordPress’s default the_title() function.

So for example, you can wrap the subtitle in some HTML tags using the first two parameters:

[php]

if(function_exists(‘the_subtitle’)) the_subtitle( ‘<h2 class="subtitle">’, ‘</h2>’);

[/php]

If you need to return the value, much like the default WordPress functions, you can use get_the_subtitle() which accepts a $post_id parameter if you need to use it outside the loop.  If you do not supply a $post_id, it will automatically grab the ID from the current post.  But if you supplied a number there, you could ostensibly use it to grab the subtitle of another post.

[php]

if(function_exists(‘the_subtitle’)) $subtitle = get_the_subtitle($post_id);

[/php]

Oh, and I left the shortcode in tact, though I can’t figure out why you’d use the shortcode instead of just straight typing into the post editor.  But if you want it, it is still:

with no spaces.

To DO:

I’m wondering if it is worthwhile to add a subtitle column to the edit screen and if I should then add it to the “quick edit”. Let me know your opinion in the comments!

Download

Now available at WordPress: KIA Subtitle at WordPress

or check it out at the KIA Subtitle github repo

Thematic 1.0.1 Upgrade

May 31, 2012

After a long wait, Thematic 1.0.1 has been live in the WordPress repositories now for a couple of days now! And some issues are starting to crop up in the forum. So far the most recurring issues have to do with the menus. Oh menus, you never cease to cause trouble.

The problem is that thematic 1.0 underwent some major changes to be compliant with WordPress Theme Review Guidelines and the change with the most impact on menus in particular is our switch to properly enqueing stylesheets and scripts using wp_enqueue_stylesheet and wp_enqueue_script. This has led to some changes to existing functions and the removal of a few old filters that didn’t make sense anymore given the new approach. You can see the massive changelog in the readme.txt file that comes with Thematic, but really, its huge, so it would be easy to miss the ones that are effecting you.

I Upgraded and Now My Menu is Broken

We’re going to need to diagnose what went wrong based on what you used to be doing and what has changed.

* Changed: Filter thematic_dropdown_options.

Were you serving your own modified version of the thematic-dropdowns.js script to tweak the widths of the dropdowns, add arrows, or change the delay on the hover? If so, then you might have been filtering thematic_dropdown_options. This filter used to work like so:

[php]
function childtheme_dropdown_options() {
$newscript_uri = "\n" . ‘<script type="text/javascript" src="’ . get_stylesheet_directory_uri() . ‘ /scripts/thematic-dropdowns.js"></script>’ . "\n";
return $newscript_uri;
}
add_filter(‘thematic_dropdown_options’,’childtheme_dropdown_options’);
[/php]

in that you needed to return the whole script tag. That is no longer the case and now you need only to return the URL of the script like so:
[php]
function childtheme_dropdown_options() {
$newscript_uri = get_stylesheet_directory_uri() . ‘/scripts/thematic-dropdowns.js’;
return $newscript_uri;
}
add_filter(‘thematic_dropdown_options’,’childtheme_dropdown_options’);
[/php]

 

* Removed: Variable thematic_use_superfish. * Added: add_theme_support('thematic_superfish')

We’ve switched to using the WordPress function add_theme_support to determine whether to load the superfish scripts. Previously there was a filter called themtatic_use_superfish, that you could target to remove the dropdown scripts if you didn’t need them.
[php]
function childtheme_no_superfish(){
return FALSE; // we don’t want any of your vegetables!
}
add_filter(‘thematic_use_superfish’,’childtheme_no_superfish’);
[/php]

or if you were being super elegant, perhaps you killed the dropdowns with this:

[php]
add_filter(‘thematic_use_superfish’,’__return_FALSE’);
[/php]

But, we’ve ditched this filter in favor of using WordPress’ theme support feature. It is an easy switch. If you don’t want to load any of the superfish, dropdown scripts then you should now do it this way:
[php]
function childtheme_no_superfish(){
remove_theme_support(‘thematic_superfish’);
}
add_action(‘thematic_child_init’,’childtheme_no_superfish’);
[/php]

Note that thematic_child_init is a new action hook, that is specifically placed to remove any theme supports added by thematic.

* Removed: Filter thematic_head_scripts.

To be fair this one isn’t in the readme as far as I can see, but the problem is similar to the issue with thematic-dropdowns.js. Maybe you were using this filter to you maybe wanted to remove all the superfish and supersubs scripts because you don’t use dropdowns. Or perhaps you were adding your own scripts here.
[php]
function childtheme_scripts($scripts){
return FALSE; //we don’t want any of your vegetable scripts!
}
add_filter(‘thematic_head_scripts’,’childtheme_scripts’);
[/php]

or if you were adding a scripts of your own, maybe you did something like this:
[php]
function childtheme_scripts($scripts){
$scripts . = "\n" . ‘<script type="text/javascript" src="’ . get_stylesheet_directory_uri() . ‘ /scripts/thematic-dropdowns.js"></script>’ . "\n";
return $scripts;
}
add_filter(‘thematic_head_scripts’,’childtheme_scripts’);
[/php]

As before, we are now using using wp_enqueue_script, so thematic_head_scripts() is now only a function that is added to the wp_enqueue_scripts hook. You can remove it entirely the same way you remove any action:

[php]
function childtheme_remove_scripts(){
remove_action(‘wp_enqueue_scripts’,’thematic_head_scripts’);
}
add_action(‘init’,’childtheme_remove_scripts’);
[/php]

or possibly you were using the override:

[php]
function childtheme_override_head_scripts(){
// absolutely no bacon here
}
[/php]

However, that is a bit of a nuclear bomb approach and will also wipe out an important script for handling comment replies, which you may or may not need. But thematic is super granular and you can use a scalpel to kill the drop downs scripts quite easily instead of using a viking war hammer with the remove_theme_supportscrap of code from earlier.

If instead, you need to load more scripts, then you should make like Thematic and use wp_enqueue_script.

[php]
function childtheme_scripts(){
wp_enqueue_script(‘bacon-script’, get_stylesheet_directory_uri . ‘/scripts/bacon.js’, array(‘jquery’), ‘1.0’, true);
wp_enqueue_script(‘guacmole-script’, get_stylesheet_directory_uri . ‘/scripts/guac.js’, array(‘jquery’));
}
add_action(‘wp_enqueue_scripts’,’childtheme_scripts’);
[/php]

If you are wondering about why the two lines are different, you can read more about how to use wp_enqueue_script in the WordPress Codex:

* Changed: Function thematic_create_stylesheet to wp_enqueue_style.
* Removed: filter thematic_create_stylesheet.

I saw this come up in the forum already. Someone was using the thematic_create_stylesheet filter to add extra stylesheets to the header. Something along the lines of :

[php]
function childtheme_create_stylesheet($style) {
$style .= ”;
return $style;
}
add_filter(‘thematic_create_stylesheet’, ‘childtheme_create_stylesheet’);
[/php]

Well that filter is gone like a bowl of my famous guacamole, so if you need to add more stylesheets, then we’ll have to add them the updated way… which by the by, will work better with any caching plugins you might be using and prevents the same style from being loaded twice (like if you were loading the supersized script’s css and then you had a plugin that was also trying to load the same stylesheet).
Thematic is now loading the main stylesheet like so:

[php]
function thematic_create_stylesheet() {
wp_enqueue_style( ‘thematic_style’, get_stylesheet_uri() );
}
add_action(‘wp_enqueue_scripts’,’thematic_create_stylesheet’);
[/php]

I can’t think of too many reasons why you’d ever need to change that. Your theme will always need a style.css in order to be a valid theme. But if you need to add more stylesheets, it is going to work just like enqueueing scripts except we use a slightly different function, wp_enqueue_style.

[php]
function childtheme_create_stylesheet() {
wp_enqueue_style( ‘blue_style’, get_stylesheet_directory_uri() . ‘/styles/blue.css’ );
}
add_action(‘wp_enqueue_scripts’,’childtheme_create_stylesheet’);
[/php]

Oh Noes! My menu is still broken!

Well, head to the support forums and start a new thread. Here is a tip for getting better support: do NOT just say “my menu won’t work”. This tells me and the other volunteers absolutely nothing and makes it impossible to help you. Be precise when describing exactly what you are trying to accomplish, what you are seeing/experiencing now, compare that to what you were experiencing before hand, and tell us anything that you might have already tried. Screenshots can be helpful as can links to your live site.

Thematic Support Forums

How to Use Multiple WYSIWYG (TinyMCE) Visual Editors in Your WordPress Metaboxes

March 8, 2012

Ever since WordPress invented the metabox, people have been trying to put the rich text editor (in WP this is provided by TinyMCE) into their metaboxes. And it makes sense. Sure us uber-geeks know the HTML tags required to make some text bold, but most of the world does not. But they do know how to click on the “B” button.  So if we’re building a theme that requires multiple blocks of content it’s nice to reuse the visual editor.

I’ve been using the WP Alchemy Class by Dimas Begunoff to build my metaboxes for a while now.  It gives a *lot *of power to build really complicated field sets, especially repeating ones.  For a long time using the visual editor in the metaboxes was elusive. Dimas wrote an article on How to Use Multiple WordPress WYSIWYG Visual Editors and it worked, up to a point.  Because TinyMCE is fickle (and despite their tagline being “Easy to Integrate”) this code didn’t work for repeating groups, which in my mind is the strength of Alchemy.

As of WordPress 3.3 you can finally use the built-in wp_editor() function for multiple editors in your metaboxes, but again these must be defined in advance.  You can’t use this function with WPA’s dynamically generated fields. So, repeatable, sortable WYSIWYG (TinyMCE) rich-text editors has been the elusive, ultimate dream of WP Alchemists. The <cough>Holy Grail</cough> of WP Alchemy. But after a lot of head-banging effort, I think I have it!

I have create a Twenty Eleven child theme that shows WP Alchemy-powered metaboxes with repeatable, sortable, WYSIWYG (tinyMCE-enabled) text editors complete with media buttons. And as a bonus, it shows a single field using wp_editor() because that also needed a little twist to work with WPA. Upload and activate the theme, then add a new post to see the boxes in action.  For the curious, and come on you know you are, the real magic is in the kia-metabox.js script. Download the sample theme from for an idea of how it works.

Fork me on github!  Perhaps we can figure out how to use the quicktags editor when the visual editor is disabled. Full tutorial to come…  maybe.

Create an Alphabetical Glossary of Posts in WordPress

February 12, 2012

Once up a time i did a client project where i had to have archives organized alphabetically.   I ended up accomplishing by adding a query variable and targeting the posts_where filter.  However, in answering a recent question at WordPress Stack Exchange I decided that it might be neater to create a hidden taxonomy instead.  I don’t know if there is any performance benefit, but the code was a little more elegant and you get prettier permalinks: site.com/glossary/a instead of site.com/?glossary=a right off the bat without the need to do any complicated htaccess rewrite rules, since everyone knows that mod-rewrite is straight up voodoo.

Creating a Hidden Taxonomy

Pretty standard function for registering a taxonomy. Just going to accept a lot of the defaults, and not worry about labels since we’re going to hide it from the back-end by setting the ‘show_ui’ parameter to false. For this example we’re going to call the taxonomy “glossary” and we’re going to assign it to posts, but we could well have done it for any custom post type.

Automatically Setting Terms for each Post on Save/Update

It’d be a pain if we had to actively remember to sort each post by its letter each time we wrote a post. I have enough difficulty just writing a post in the first place. But with some code we can automatically pop off the first letter of the post title and assign that letter as the term in our “glossary” taxonomy. The following is the pretty standard function for saving information from a metabox, which works perfectly for our case even though we don’t have a visible metabox.

Auto-Assigning Terms to existing posts

If you’ve had a blog for a while and have a lot of posts the idea of going back and manually saving the posts again sounds worse than pulling our your toenails.  So you can run a little function to do it automatically.  Ideally, if this were a plugin, it’d run on the plugin’s activation hook.  Since it’s not you can just drop it into your functions.php and then reload your site. Thanks to the transient check you can leave it in there and it won’t run again. Basically what it will do it grab all your posts, loop through them all, pop off the first letter of the title and assign it to the “glossary” taxonomy.

Finally, Creating the Alphabet “Menu”

Now that we have assigned a term for each existing post and for every post to come in our custom taxonomy, we should display an alphabet menu…. or some way to access the different Letter archives.  This was the one place were the code was not 10x more elegant than in my first iteration because there was no easy way to test whether a term had a post in it.  Usually, yes, it would… but if you changed a post name and there were no other posts under a certain letter you could come up with an empty section.  So what I did was get all the terms in the taxonomy with get_terms which hides empty terms by default, loop through that data and store it in an array, then check each letter of the alphabet against that array.  To avoid running through that every single page load, I used the transient API to store the resulting array of alphabet terms.  This array refreshes whenever a post is updated (this actually happens in an earlier code block for the kia_save_first_letter() function. For my original project I wanted to have the letters with posts have an active link and the letters without posts in that section just have the letter.  Something like: A B C D** E** …. and onwards, so I have re-created that effect.

Future Improvements

One thing I’d like to improve upon would be ensuring that the first letter I’m popping off with the substr PHP function is actually a letter… or maybe a number, but not a character.  I’d also like to get it to skip words like The, An, and other pointless words that don’t really reflect on the subject.  But then this isn’t a solution for everyone… if you want to make sure that “A Post about Bacon” and “The Bacon Post” show up in the same archive, well you should tag them in the Bacon tag and not hope that they show up alphabetically in the right place.  Still it has its uses.  Let me know of any improvements you make!