Easy WordPress Theme Template Identification

I’ve been developing a new commercial WordPress theme, and one of the main goals I’ve had in mind is to make customizations as easy as possible for customers. One sticking point and a question I often receive in my support forums, is “where do I find XYZ…”. This technique automatically adds HTML comments around the various template code blocks, making it easy to identify the source of any code within the template.

The basic idea is this: Each template is wrapped in HTML comments so that the output on the front end looks something like this (simplified):

<body>
    <header>
      ...
    </header>

    <div class="main">

        <!-- begin archive.php [theme_name] -->
        <div class="primary">

              <!-- begin content.php [theme_name] -->
              <article class="post">

              </article>
              <!-- end content.php -->
        </div>
        <!-- end archive.php -->

        <!-- begin sidebar.php [theme_name] -->
        <div class="sidebar">

        </div>
        <!-- end sidebar.php -->

    </div>
  

    <footer class="site-footer">
      ...
    </footer>

</body>

This gives the developer/customer an immediate reference for where to start looking in the theme files in order to locate the appropriate spot to make changes/override in a child theme. Of course, you could do this with static HTML comments in each template – I’ve done this in my previous theme, and it has definitely helped customers. The downside is that every time you make a new template, if you base it off of an existing template (which I expect is a common scenario), you have to remember to update the comments. That can be a bit tedious, and failure to do so can result in inaccurate comments, and the last thing we want is to send the customer on a wild goose chase. This technique avoids that.

Sidenote: The sidebar template, sidebar.php, the header template, header.php, and the footer template, footer.php, are of course called within the archive template, archive.php – so the HTML comments aren’t technically in the proper locations. The comment locations used here represent the practical divisions within standard WordPress themes in order to provide users with the most useful guidance, rather than the most accurate technical locations.

Of course, sometimes the classes applied to the body tag can be enough to identify the template for advanced users, but the source of a template file can still be ambiguous if a child theme is in use, or when we are using nested content templates. This technique makes it immediately clear which template is producing which code.

We’ll define two functions that dynamically output the template location within the theme. Then we just add these functions to the start and end of each template file to act as bookends for the code. We can copy these functions as many times as we want, and they will always remain accurate within the template they appear (just remember that wherever the __FILE__ magic constant is invoked is the location that will be printed – that’s why __FILE__ must be passed as a parameter). Moreover, if we want to change the structure of the comment, or remove them altogether based on a setting, that becomes trivial to accomplish. Here are the functions, which you should namespace:

function begin_template( $file ){
	?>	<!-- begin <?php echo basename( $file ) . " [".basename( dirname( $file ) ) ."]" ; ?> -->
	<?php
}
function end_template( $file ){
	?><!-- end <?php echo basename( $file ); ?> -->
	<?php
}

Then within the template files, they are called like this:

<?php tinderbox_begin_template( __FILE__ ); ?>
<?php tinderbox_end_template( __FILE__ ); ?>

Each function determines the file name and prints it within an HTML comment. For the beginning comment, we also print out the directory in which the template appears – this makes it easy to determine if the template is from the parent or child theme.

Here’s a basic example of how index.php might look (this is Underscores-based):

get_header(); ?>
		
		<?php begin_template( __FILE__ ); ?>
		<div id="primary" class="content-area span8">
			<div id="content" class="site-content" role="main">

			<?php if ( have_posts() ) : ?>

				<?php tinderbox_content_nav( 'nav-above' ); ?>

				<?php /* Start the Loop */ ?>
				<?php while ( have_posts() ) : the_post(); ?>

					<?php
						/* Include the Post-Format-specific template for the content.
						 * If you want to overload this in a child theme then include a file
						 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );
					?>

				<?php endwhile; ?>

				<?php tinderbox_content_nav( 'nav-below' ); ?>

			<?php else : ?>

				<?php get_template_part( 'no-results', 'index' ); ?>

			<?php endif; ?>

			</div><!-- #content .site-content -->
		</div><!-- #primary .content-area -->
		<?php begin_template( __FILE__ ); ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

The functions bookend the meat of the template, excluding headers, sidebars, and footers. In the content-{type}.php templates, the comment functions would wrap the entire contents of the file.

Now we can make as many copies of this template as we want, and never worry about updating the comments. Nifty.

I think if more developers adopt this type of commenting (in addition to standard code commenting), it’ll go a long way toward customers becoming self-sufficient in sourcing template files and making their own customizations. Plus, I find it makes things much easier for myself during the development process.

How to add links to WordPress image captions

The WordPress media manager allows you to add captions to your images, which can be inserted into your post content wrapped in the caption shortcode.

You can see that I’ve placed anchor tags in the photo caption to link to the photo credit:

Photo credit: <a href="http://www.flickr.com/photos/nattu/2735064420">nattu</a></code>

When you click the “Insert into Post” button, you end up with this markup in your editor:

[ caption id="attachment_1133" align="alignleft" width="300" 
caption="Photo credit: <a href=&quot;http://www.flickr.com/photos/nattu/2735064420&quot;&gt;nattu&lt;/a&gt;"]
<a data-rel="prettyPhoto" title="The Entrance" href="http://localhost/agility/wp-content/uploads/2012/03/TheEntrance.jpg">
<img src="http://localhost/agility/wp-content/uploads/2012/03/TheEntrance-300x199.jpg" alt="" title="The Entrance" width="300" height="199" class="scale-with-grid size-medium wp-image-1133" /></a>[/caption]

Skip to the code solution

The Problem

The issue is that all the HTML entities in the caption attribute (specifically, the anchor tags) are encoded. That is, instead of

Photo credit: <a href="http://www.flickr.com/photos/nattu/2735064420">nattu</a>

we have

Photo credit: &lt;a href=&quot;http://www.flickr.com/photos/nattu/2735064420&quot;&gt;nattu&lt;/a&gt;

As a result, instead of getting the desired output in our caption:

Photo credit: <a href="http://www.flickr.com/photos/nattu/2735064420">nattu</a>

We get the encoded HTML markup instead:

Photo credit: &lt;a href=&quot;http://www.flickr.com/photos/nattu/2735064420&quot;&gt;nattu&lt;/a&gt;

The Solution

Now, the HTML entities have to be escaped in order to safely place them in the caption=”” attribute of the caption shortcode (or at least the double quotes do), and in any event it’s very inconvenient to decode the entities manually. What we’ll need to do is decode them programmatically when the shortcode is processed at run time.

Helpfully, WordPress’s img_caption_shortcode function (wp-includes/media.php) includes a filter that allows us to hook in and override the caption. Here’s the original function:

/**
 * The Caption shortcode.
 *
 * Allows a plugin to replace the content that would otherwise be returned. The
 * filter is 'img_caption_shortcode' and passes an empty string, the attr
 * parameter and the content parameter values.
 *
 * The supported attributes for the shortcode are 'id', 'align', 'width', and
 * 'caption'.
 *
 * @since 2.6.0
 *
 * @param array $attr Attributes attributed to the shortcode.
 * @param string $content Optional. Shortcode content.
 * @return string
 */
function img_caption_shortcode($attr, $content = null) {

	// Allow plugins/themes to override the default caption template.
	$output = apply_filters('img_caption_shortcode', '', $attr, $content);
	if ( $output != '' )
		return $output;

	extract(shortcode_atts(array(
		'id'	=> '',
		'align'	=> 'alignnone',
		'width'	=> '',
		'caption' => ''
	), $attr));

	if ( 1 > (int) $width || empty($caption) )
		return $content;

	if ( $id ) $id = 'id="' . esc_attr($id) . '" ';

	return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}

add_shortcode('gallery', 'gallery_shortcode');

We’re just going to hook in and use the same code, but add a line of our own to decode the HTML tags.

$caption = html_entity_decode( $caption );

The Code

So, our final function, which I’ve placed in functions.php, looks like this:

//Our custom caption shortcode function is based on the WordPress Core version with a small change
function custom_img_caption_shortcode( $a , $attr, $content = null) {

	extract(shortcode_atts(array(
		'id'	=> '',
		'align'	=> 'alignnone',
		'width'	=> '',
		'caption' => ''
	), $attr));

	if ( 1 > (int) $width || empty($caption) )
		return $content;

	$caption = html_entity_decode( $caption );  //Here's our new line to decode the html tags

	if ( $id ) $id = 'id="' . esc_attr($id) . '" ';

	return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
	. do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}
//Add the filter to override the standard shortcode
add_filter( 'img_caption_shortcode', 'custom_img_caption_shortcode', 10, 3 );

And that’s it! Just pop that code into your functions.php and you should be able to add links to your photo captions. If anyone knows a better way of doing this, let me know in the comments. Enjoy!

How to Add a Custom Class to a WordPress Menu Item

This is a question I get a lot related to UberMenu – WordPress Mega Menu Plugin, though it’s actually baked into WordPress Core. It’s a very powerful feature, as it allows you to target either a single menu item or a group of menu items with a single class. However, the option is hidden from the UI by default. In order to add a class to a menu item, you first have to reveal it.

1. In Appearance > Menus, click the Screen Options tab

Click the Screen Options tab

2. Under Show advanced menu properties, check CSS Classes

Check CSS Classes option

3. Now expand any menu item to reveal the CSS Classes (optional) text input.

CSS Classes text input

4. Enter your class name and save your menu to apply the class to the menu item

The class will be added to the LI (list item) element, the same element that has the menu item ID attached. You can then style your item like this, where .menu is replaced by the class used for your menu:

/* Target the menu item LI */
.menu li.myClass{
  /* Margin might go here */
}
/* Target the menu item Anchor (link) */
.menu li.myClass > a{
  /* Colors, font sizes, would normally go here */
}

/* Target the menu item LI in UberMenu */
#megaMenu ul.megaMenu li.myClass{

}
/* Target the menu item Anchor (link) in UberMenu */
#megaMenu ul.megaMenu li.myClass > a{
  /* Colors, font sizes, would go here */
}

Remember that you may need to increase your selector specificity or use the !important flag in order to ensure that your new styles are applied.

5. Enjoy even more customization control over your menu!

Note that this is a standard WordPress feature and works with or without UberMenu.

What’s new in UberMenu 2.0? (A Responsive, More Flexible WordPress Mega Menu)

It’s been a year since I first released UberMenu – WordPress Mega Menu Plugin. In that time it has sold almost 4,000 copies and continues to be an extremely popular WordPress menu solution. I’m so lucky that this plugin has had such success – it has allowed me to move my business to digital goods development full-time, which has been wonderful. I’d like to thank all of the great customers who have bought UberMenu, I truly appreciate it.

Are you upgrading from an old version of UberMenu to version 2.0? Please read the Important Upgrade Instructions

In the last year I’ve gathered a lot of insight into the menu process through my interactions with the many users I’ve supported. I’ve learned a lot about what features users make the most use of, what tends to cause confusion, common customization needs, and a whole lot more.

I’ve spent the last month and a half distilling this accumulated knowledge into what is now UberMenu 2.0, refining functionality and enhancing the feature set. My goals with UberMenu 2.0 have been:

  1. Increase the intuitiveness of the plugin
  2. Improve areas that tend to cause customer confusion
  3. Increase javascript efficiency
  4. Increase plugin extensibility
  5. Improve menu design, robustness, and flexibility

I’m very proud of the new UberMenu 2.0, which represents a huge time investment to deliver major enhancements. Here are some of the new features in UberMenu 2.0.

Enhanced CSS

The basic CSS structure of UberMenu has been torn down and rebuilt to provide an even stronger foundation for the menu. This means menus act more intuitively out of the box, and customizations are simpler to implement. It also means that UberMenu works excellently as a pure CSS menu with full-width submenus.

More Efficient Javascript

A stronger CSS foundation means less calculations in the javascript, which leaves us with a much lighter weight and more efficient jQuery plugin enhancing UberMenu. The javascript has also been rewritten as a jQuery plugin, implementing jQuery best practices. The upshot is that UberMenu now loads and runs faster than ever.

Full Width Submenus and Defined Columns

One part of UberMenu 1.x which was less intuitive than it could be was column formatting. Columns were sized entirely based on their content size, which led to some interesting corner cases. While these issues were easily resolvable via custom CSS, for users without a working knowledge of the box model, such strange behavior was frustrating and confusing.

In UberMenu 2.0, columns can be sized in two ways, on a per-submenu basis: naturally, or in grid based columns. In a natural layout, each column is sized to its contents, and each column may be a different width. This is great for single-row submenus. For multiple-row submenus, UberMenu 2.0 adds the ability to set a submenu to be full-width, and apply a specific number of columns to the submenu. These columns will be uniformly sized, and extend the entire width of the submenu automatically.

I believe this new system is much more intuitive and will provide users a much better experience when wrangling their submenus into the formats they desire.

Grid Columns

Fully Responsive Menus

When designing Agility HTML5 Template, I spent a long while studying responsive design best practices. UberMenu makes use of that knowledge to deliver a responsive mega menu. As the viewport changes, UberMenu’s contents size intelligently to optimize display at each size. (Note this can be disabled for non-responsive themes).

Responsive - Mobile LandscapeResponsive - Mobile Portrait

iPhone and iPad Compatibility

Going hand in hand with the responsive mega menu enhancements, UberMenu is now even more compatible with iOS devices, delivering an intuitive user experience for responsive themes.

More Flexibility

Another goal of UberMenu 2.0 is to build in some of the most common customizations into the Control Panel, to avoid core UberMenu edits. Now you can:

  1. Customize dropdown animation speeds
  2. Trigger via hover in addition to hoverIntent and click
  3. Customize hover intent timing
  4. Disable image resizing
  5. Enable or disable loading UberMenu on registration and login pages

Fresh menu skins

Both design trends and my own design skills have advanced a lot in the last year. UberMenu 2.0 features refreshed menu skins, with progressive CSS3 enhancements. The designs are now cleaner and more modern (the old designs are still included for legacy use, if desired).

Watch for more menu skin options coming soon!

Rewritten Style Generator

The UberMenu Style Generator has been completely rewritten to make use of LESS via lessphp. This means more consistency and easier upgrades. The new Style Generator also has the ability to write your custom style to an external stylesheet rather than including the CSS in the site header (though that is still an option).

A note on backwards compatibility

In developing UberMenu 2.0, I’ve made every effort to maximize compatibility with previous UberMenu installations. All menu items and their options, as well as UberMenu Control Panel options, will remain intact. Unfortunately, some sacrifices had to be made in the name of progress. Because the underlying CSS structure has been enhanced, some types of customizations may no longer appear as desired and may need to be reworked – though in some cases they will no longer be necessary at all! Specifically, submenu positioning and column resizing may need to be readdressed. However, all previous class names and IDs have remained consistent to minimize the impact and make the transition for users from 1.x to 2.0 as smooth as possible.


Well, that’s about it. I hope UberMenu customers enjoy the upgrade! It’s been a long process getting to this point, and I’m very pleased with the results. Feedback is always welcome and will be considered for future releases whenever possible.

Thanks again to all UberMenu customers for your business!

ReplyPantry – Text in a Can for the Envato Marketplaces

ReplyPantry is a Google Chrome Extension that allows Envato Marketplace users to insert customized text snippets into forum posts or item comments.

Once you install ReplyPantry you’ll see the can icon below your reply boxes in the forums – and above in the item comments. Click the can icon to show the canned text snippets (“cans”), and click a can title to insert that canned text. You’re able to add, save, edit, and remove cans. Hopefully it’s fairly intuitive.

If you’re using Google Chrome, clicking the download link should allow you to download and prompt you to install the extension.

How to create a mail counter for Contact Form 7

Here’s an easy way to set up a counter for your contact form using Contact Form 7 and Contact Form 7 Dynamic Text Extension. Basically, we’re setting up an action that will increment a counter each time an email is sent. We’re grabbing that count and placing it in the email using CF7 DTX.

Add the functional code

First, here’s the code to add (anywhere, but functions.php works well. It’ll be added to CF7 DTX some time down the road hopefully).

//Define the key to store in the database
define( 'CF7_COUNTER', 'cf7-counter' );

//Create the shortcode which will set the value for the DTX field
function cf7dtx_counter(){
    $val = get_option( CF7_COUNTER, 0) + 1;  //Increment the current count
    return $val;
}
add_shortcode('CF7_counter', 'cf7dtx_counter');

//Action performed when the mail is actually sent by CF7
function cf7dtx_increment_mail_counter(){
    $val = get_option( CF7_COUNTER, 0) + 1; //Increment the current count
    update_option(CF7_COUNTER, $val); //Update the settings with the new count
}
add_action('wpcf7_mail_sent', 'cf7dtx_increment_mail_counter');

Configure the Contact Form

Next, we set up our contact form. We’re going to add a new hidden dynamic field to it using CF7 DTX and the new shortcode we just wrote. Here’s what that code would look like in the Contact Form 7 Form Settings:

[dynamichidden cf7-counter "CF7_counter"]

Finally, we want to include the count in the message we receive, so we’ll add it to the CF7 Message Body field:

Count: [cf7-counter]

Some Notes

  • The counter only increments when the mail is actually sent. Form loads and failed sends won’t trigger the count to increase.
  • If two contact forms are submitted without reloading the page, the count will be incremented properly, but it won’t be reflected in the email. This is because the count that is sent in the email is only updated when the page loads. To update it without a page load, you’d need to write some JS that hooks into CF7’s send callbacks.

That’s about it – enjoy! Let me know in the comments if you find this useful (or run into any trouble).

Apple-style Menu Skin for UberMenu

This skin was for UberMenu 1.x, and is now a bit obsolete. Please look for new UberMenu 2.0 Skins coming soon!

Here’s a free CSS3 Apple-style menu skin for use with UberMenu – WordPress Mega Menu Plugin.

How to install

  1. Copy the contents of the download to your plugins/wp-uber-menu/styles/skins/custom.css file.
  2. In Appearance > UberMenu > Style Settings, set Style Application to Preset
  3. Set Style Preset to Custom

Enjoy!

SevenSpark.com Site Redesign & Updated Branding

Well, it’s been in desperate need of it for a while, but sevenspark.com has finally been updated with a brand new custom theme and some branding updates. The new theme focuses on the latest postings, which reflects my intention to generate content for the site much more often. I intend these posts to share jQuery, CSS, and PHP snippets and experiments that I hope others will benefit from – the first one will be published soon.

The new design is intended to be much more usable in addition to being a lot nicer to look at. Much greater attention was paid to typography and white space, and I hope that shows through in the readability of the site.

The site also features custom post types for Products and Portfolio items, which will make it much easier to keep these galleries updated.

The new theme makes wide use of HTML5 and CSS3, and is based on the Toolbox framework. It also makes use of the prettyPhoto jQuery plugin, WordPress SEO by Yoast, Contact Form 7, Twitter Widget Pro. and the WPZoom Social Media Icon Set. Many thanks to each of these fine resources.

Along with the site update comes a redesigned logo, which I’m really pleased with. I think it’s a lot cleaner and sharper. A new SevenSpark Facebook page also accompanies the site now, and you can grab the RSS feed via feedburner.

Hope you enjoy the site! Feel free to let me know what you think in the comments – be nice, now 😉

YARPP Featured Image Template

Demo Code

YARPP (Yet Another Related Posts Plugin) for WordPress is a great related posts plugin. With one of my recent products, Scroll Checkpoint, I wanted to create an example of a recent posts sliding dialog with featured image thumbnails, and decided on YARPP as my best solution.

YARPP 3 includes a wonderfully extensible template system that allows you control the details of how related posts are displayed. I was able to create just the look I wanted, and I decided it would be worth sharing this template so that others could make use of it.

The code is in 3 parts:

  1. functions.php – The code that registers the features image size we’ll use in the template
  2. yarpp-template-thumbnail.css – The styles used in the Scroll Checkpoint demo – of course, these can be modified and added to any stylesheet.
  3. yarpp-template-thumbnail.php – The actual template, which creates the HTML for each related post.

All the code is available in its entirety on GitHub’s gist (click Code above).

Enjoy!