Categories
WordPress

Challenges with the new method for inheriting parent styles in WordPress child themes

During the past month or so a new method for inheriting parent styles in WordPress child themes has been established, replacing the old method of importing parent styles with an @import call in the child theme style.css file.

The new method involves enqueueing first the parent and then the child style.css file through a functions.php file in the child theme.

While at first glance this seems a valid and much improved approach, further testing has uncovered an inherent flaw in its logic: The new method makes several assumptions about the scenario in which it would be used that make it hard to use and prone to failure.

The current (new) method is described as follows in the Codex:


<?php
add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX);
function enqueue_child_theme_styles() {
    wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
    wp_enqueue_style( 'child-style', get_stylesheet_uri(), array('parent-style')  );
}

The Theme Handbook describes a variant of this same approach:


<?php
function get_parent_theme_css() {
  wp_enqueue_style( 'your-child-theme-name', get_template_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'get_parent_theme_css' );

In both cases one important assumption is made: That the parent theme has one main stylesheet with the filename “style.css” and that it does not use any other stylesheets. This is not a realistic situation, and in cases where the parent theme relies on stylesheet dependencies it can cause some serious issues.

What happens

First, let’s look at each of the examples and see what happens:

In the Codex example we set up an action that hooks onto the wp_enqueue_scripts event and calls in a function. The function contains within it two calls to enqueue first the parent theme style.css file and then the child theme style.css file. This results in the parent theme style.css file loading first, then the child theme style.css file, and you get page markup where new styles added to the child theme style.css file will override the parent theme styles. This is as intended and in line with how things worked with the @import function. This works as long as all parent theme styles are contained within a file called “style.css” which as we will see in a bit is not always the case.

The Handbook example sets up the same way but only calls the parent theme style.css file. Because of how WordPress works, this overrides the inherent logic and prevents the child theme stylesheet from loading. As a result any style change added to the child theme style.css file will not take effect making changes to styles through this file unavailable. This is likely an omission in the documentation so not worth dwelling on further.

The Problem of Dependencies

Now for the problem: As indicated above not all parent themes operate with a single style.css file that contains within it all styles. In many cases themes use a series of stylesheets to achieve optional layouts or other effects. These are normally enqueued as dependencies to ensure everything is added in the correct order.

Take this example: A theme ships with two layouts, right sidebar and no sidebar. To achieve this without cluttering up the style.css file with two different sets of layout styles the theme developer has separated out the layout styles in their own stylesheets under a dedicated folder. This is common and the recommended approach in the _s starter theme.

To get it all to work in the parent theme we have something like this:


<?php
// Create function to enqueue styles
function themename_scripts() {
  // Register main stylesheet with the handle 'themename-style'
  wp_register_style( 'themename-style', get_template_directory_uri().'/style.css' );

  // Test for nosidebar template or no sidebar and select correct layout stylesheet.
  // Layout stylesheet is enqueued with the label ‘themename-layout’ and made dependent on 'themename-style' above
  if (is_page_template('page-templates/page-nosidebar.php') || ! is_active_sidebar( 'sidebar-1' )) {
    wp_enqueue_style( 'themename-layout' , get_template_directory_uri() . '/layouts/no-sidebar.css', array('themename-style') );
  } else {
    wp_enqueue_style( 'themename-layout' , get_template_directory_uri() . '/layouts/content-sidebar.css', array('themename-style') );
  }
}
add_action( 'wp_enqueue_scripts', 'themename_scripts' );

The function above is typical and straight-forward: When the parent theme is loaded a test is run for the current layout condition and based on its result one of the two layout stylesheets are enqueued. These stylesheets are made dependent on the main style.css file which has been registered with the handle “themename-style”. When a page is loaded the dependency (style.css) is loaded first,, then the layout styles.

This means for the theme to display properly with the correct layouts it is the layout styles that are called, not the style.css file.

Now consider the proposed approach in the codex: Here the child theme explicitly calls for the main stylesheet – style.css. That means when a child theme is activated the layout styles are not loaded!

A possible (but not user friendly or uniform) solution

The problem described above is caused by the assumption that the parent theme uses the style.css file as its only stylesheet and ignores other circumstances like a theme that uses dependencies. To solve this problem the approach must be changed to something like this:


<?php
function enqueue_child_theme_styles() {
  wp_enqueue_style( 'child-style', get_stylesheet_uri(), array('[parent_theme_name]-style') );
}
add_action( 'wp_enqueue_scripts', 'enqueue_child_theme_styles', PHP_INT_MAX);

In this example we are enqueueing only the child theme stylesheet and making it dependent on the parent theme stylesheet stack in whatever way that is set up. This preserves any dependencies in the parent theme and provides the correct ordering of all stylesheets. The problem of dependencies is solved, but this solution puts the onus on the child theme author to know what stylesheet is “in control” of the parent theme and know what its label is. That means tunnelling into the parent theme functions.php file and finding the correct enqueue function – something requiring a level of skill previously not needed for building child themes. As a result the threshold on getting started with building child themes and eventually themes becomes much higher than it used to be.

Moving forward

The change in recommendation about how to inherit styles from parent themes brings up important questions about the role of child themes in the overall training philosophy of WordPress. Some would argue increasing the difficulty level of creating child themes as this new approach does is a good thing because it takes away some of the “hand holding” that in some cases leave users with the ability to do things they do not fully understand. On the other hand increasing the difficulty level also makes entry into the space and non-destructive customization of themes harder, something that goes against the original reasoning for introducing child themes in the first place.

As I see it we need to provide a simple and consistent approach to creating child themes and inheriting parent theme styles that does not require this in-depth understanding of how WordPress themes work. To facilitate this a new function or filter could be created to get parent- and child theme stylesheets queued up correctly.

In the end there are only three scenarios in play here that need to be made available:

  1. Child theme only uses its own style.css file. No inheritance.
  2. Child theme loads parent theme styles as they are loaded in the parent theme and then loads its own style.css file to add / override styles.
  3. Child theme only uses parent theme styles and is built to add other features that do not include CSS.

And this means the new function or filter would only have to do one of three things:

  1. Load only the child theme style.css file
  2. Load the full stack of parent theme stylesheet files as they are loaded in the parent theme, then the child theme style.css file
  3. Load only the full stack of parent theme stylesheet files as they are loaded in the parent theme

How exactly this function or filter would be built should be handled by developers wiser than myself.

Categories
Lynda.com WordPress

Start with a Theme: Twenty Fourteen – new course on lynda.com

Learn how to use the Twenty Fourteen theme for WordPress in this lynda.com course by Morten Rand-Hendriksen

Get the most out of the new Twenty Fourteen magazine-style theme that ships with WordPress 3.8 with my new lynda.com course Start with a Theme: Twenty Fourteen. This new theme has a lot to offer if you know how to use it properly, and in the course I take you through all the features, functions, and weird side effects of using this theme.

From the site:

“All great WordPress sites start with a great theme. Twenty Fourteen is the default: a new, magazine-style theme with a heavy focus on images and content. In this quick course, Morten-Rand Hendriksen walks through the setup and configuration of Twenty Fourteen, and then helps you get the most out of advanced options such as the featured content grid or slider, custom menus and sidebars, and featured images.

If you’ve updated to WordPress 3.8 you have Twenty Fourteen installed already and it’s worth a good look. So go check out Start with a Theme: Twenty Fourteen and get your WordPress site started for the new year!

If you don’t already have a lynda.com subscription you can get a 7 day free trial by following this link: lynda.com/trial/mor10

Categories
AMA

Q&A: Child theme bloat and when to build a new theme

I got these questions from a lynda.com viewer earlier today. They are fairly common so here are the questions and my answers. Keep in mind that everyone who works with WordPress or on the web in general has strong preferences one way or the other, so if you disagree with anything I say, leave it in the comments and let’s discuss!

Now for the questions:

I wondered if I could trouble you to ask just two broad/philosophical questions regarding child-themes? These are pretty “general interest” questions….

  1. If it includes a lot of CSS/template files, does a child theme eventually slow down the loading of a site? It seems that it would, since the child theme is overriding the parent theme, not replacing it. Is this true?
  2. At what point should I be taking a theme (like twentyten or other) as a starting point and build my own theme, rather than building a child theme? It seems that, at some point, if one overrides much of the original theme, there seems to be less benefit gained from parent theme updates etc. and an increased risk of having a really bulky site. (Though I’m not sure I’m experienced enough to build a complete theme quite yet without missing something important – like security etc.)

I’d be really interested to hear your thoughts, if you have a couple of minutes to share them.

Thanks, Jodi

Child Theme Bloat

A child theme doesn’t really bog down the site any more than a regular theme, even if it is completely rewriting all of the parent theme. Let me break it down for you:

If you use @import or another method to load the original stylesheet, then you are loading two stylesheets, but WordPress stylesheets are relatively small and uncomplicated so it’s not that much of a tax on the server. If you roll your own styles entirely, you are just loading one stylesheet.

The parent theme functions.php file will always load along side your child theme functions.php file, but again these files are relatively small so the tax is negligible.

If you make any other template files in your child theme (header.php, index.php, new_cusom_file.php) these will be loaded in place of or in addition to the parent theme files. In other words you’ll never load both the parent theme and the child theme template file and then only display the contents of one of them.

Themes from scratch

As for when you want to build a theme from scratch, that’s a bit more complicated to answer. I build all my themes from scratch because I want full control over everything. I always work from custom designs created to match client or project criteria and rarely start off with something that can be easily built from an existing theme. I’m also obsessed with clean code, standards, and modern approaches so building from scratch every time allows me total control and room to always stay on the bleeding edge of what is being done.

If you design a site from scratch and want it to do specific things, building a theme from the bottom up is often a better idea. But, if you find a theme that already has the majority of what you need, customizing it with a child theme is a lot quicker and easier and will make upkeep easier to handle.

If you want to build your own theme from scratch there are many places you can start. I personally like to start with as little interference as possible so I use a highly personalized version of the _s (“Underscores”) theme. _s is about as stripped down as you can get and to use it you have to do a lot of work, but you also have complete control.

If that’s too stripped down for your tastes there are other great themes to start with including Toolbox. Some developers prefer starting with frameworks like Responsive, WP Fondation, WP Bootstrap, or others, but I think these are colossally overloaded and end up bringing a whole new range of complications.

I have no perfect answer for you on this one. My best suggestion is to master the art of the child theme and then take those skills and apply them to a starter theme like _s.

Hope that helps!

Categories
Speaking Engagements Tutorials WordPress

WordCamp Victoria Presentation: 10 Theme Hacks to Improve Your Site


Above is the slide deck for my WordCamp Victoria presentation entitled “10 WordPress Theme Hacks to Improve Your Site”. Unlike my regular presentation this one is entirely slides based which means if you just read the slides, you’ll get the gist of it. Below are all my code examples along with links to further information, example sites and related tutorials to give you some context. Knock yourself out!

Replace Site Title with a Linked Image

This is my number one pet peeve. When people visit a site they intuitively expect the logo or header image to be a link back to the home page, and it should be. When it’s not they (and I) get annoyed. Making your header image link back to your home page is not hard. All you have to do is wrap the header image code in a simple anchor tag that leads back to your root URL and you’re good to go. For simplicity the code looks like this:


<a title="<?php get_bloginfo( 'name' ); ?>" rel="home" href="<?php echo home_url( '/' ); ?>">

… the image code …



For a more in-depth explanation check out the tutorial Twentyten Header Image as Home Button.

Enable WordPress 3 Custom Menus

The WordPress 3 custom menu function is built into the TwentyTen theme and most newer themes, but older themes usually just have hard-coded menus. Adding WP 3 custom menus to a theme is not hard though. It requires a function call in the functions.php file and a template tag in the template file of your choice (usually header.php and/or footer.php). Here’s that code:

In functions.php:


register_nav_menus(
        array(
                'menuName' =>__('Menu Name'),
                ' primary' =>__('Primary Menu'),
                '2ndMenu' =>__('2nd Menu'),
        )
);

Where menuName is the identifying slug for WordPress and Menu Name is the actual displayed name in WordPress Admin.

To display a menu you can either call it based on the slug:


<?php 
        wp_nav_menu(array(
                'theme_location' => 'primary'
        )); 
?>

… or the name defined in the Menus admin area:


<?php 
        wp_nav_menu(array(
                 'name' => 'Menu Name'
        )); 
?>

Menus Outside the Box

Menus don’t have to be regular boring one or two word one-line elements. Because WordPress allows HTML in the Navigation Label you can add more interesting designs like we did on the 12×12 Vancouver Photo Marathon site. On this site we added a simple span tag around the text that displays under the menu heading and then used CSS to change how it displays. Sorry, no code examples – it’s just straight up CSS and out of context it makes no sense.

WordPress 3 Custom Background Images and Colours

The TwentyTen theme introduced a very cool custom background function built right into the admin interface (under Appearance -> Background). This is not a function found in TwentyTen but a core function found in WordPress. That means you can activate it in any theme. All you have to do is call it from the functions.php file:


add_custom_background();

The function injects CSS style code right into the HTML pages which means it’ll override your theme CSS file no matter what. That in turn is why it’ll work on any theme as long as you run WordPress 3.0 or higher.

Adding Featured Image (post-thumbnail) Functionality

Featured images are great, if you know how to use them. They also do way more than just displaying thumbnails (which is why I think the function should be renamed).

To activate the function add the following code to your functions.php file:


add_theme_support( 'post-thumbnails' );

This will add the function to you Admin panel. To display the featured image (in the size you want) in your theme use one of the following functions:


<?php the_post_thumbnail(); ?>

Variations:


<?php the_post_thumbnail('thumbnail'); ?>




Custom Page Templates

Custom page templates allow you to individualize the look of different pages on your site. They can be used to create custom front pages, differentiated legal pages or even custom query pages that pull in posts from multiple categories.

A custom page template is basically a regular page template with a commented out tag at the very top that looks like this:


<?php 

/* Template Name: Whatever */ 

?>

Custom Category Templates

Custom category templates can be used to create differentiated category index sections in a site. Some good examples are the Reeltime Videoworks show reel page and testimonials page and Design Schooled Kids’ press page.

A custom category template can be made in one of two ways. Either create a file with the name category-ID.php where ID is the ID number of the category or category-slug.php where slug is the slug for the category. These files will automatically become the category tempaltes for the defined categories.

Custom Header, Sidebar and Footer

You can also create custom headers, sidebars and footers sort of the same way. You make and call them the same way. For example if you want a custom header you create a new header file called header-custom.php and then call it using the standard get_header() function with a small difference:


<?php get_header('custom'); ?>

where ‘custom’ can be anything.

Better Context Links

One of the things that bug me about standard WordPress themes is that they display links to the next and previous posts in the single post view. These links don’t really provide a lot of value. Instead you should be displaying the two latest posts from the current category. So I made a small theme add-in you can dump into your theme for some better context. The add-in adds links to the two latest posts in the current category including the title, publishing date and short description. To install it download the related.php file here (right-click and choose “Save As” – it’s a straight up php file), add it to your theme directory and call it using the following code in your single.php file:


<?php get_template_part('related'); ?>

That’s all you have to do.

Categories
CSS Web Standards WordPress WordPress Themes

Typograph – new WordPress Theme

I’ve closed the comments for this thread to consolidate all comments for the different versions of the Typograph theme in one place. Please leave all your comments at the Typograph page which can be found by clicking here.

I’ve been planning to launch a proper free WordPress theme for some time now but there have always been major projects in the way. This week I had some extra time so I sat down and developed the Typograph theme which is now available for anyone to use. For free.

The theme is as simple as possible with clear separation between the content and the sidebar, a calm gray and white design with popping red links, a tabbed sidebar box with navigation, search and other important elements and some other styling for increased readability and better navigation. It complies with the new WordPress standard elements like image captions and Gravatars and even has a customizable ad space directly under the first post on the front page. And last but not least, Typograph is fully XHTML and CSS standards compliant.

Download the Typograph theme from the WordPress Theme Directory here!

See a demo of the Typograph theme here

No images

Right before I began the design of this theme, Spyremag published an article about 5 ways to break your design habits, one of which was to design a site using no images. Seeing as I’ve become somewhat obsessed with CSS over the last year it seemed only appropriate to follow this advice and create a no-images theme. Not only would this be a bit of a challenge because I ususually use a lot of images to make my designs more vibrant, but it would also put my coding skills and my understsanding of WordPress themes to the test.

Styled from scratch

Over the last several months I’ve been refining and customizing a copy of the Sandbox WordPress theme to develop an ideal platform for quick and easy WordPress theme design. The plan is to create a “God Theme” if you will that has all the bells and whistles installed and ready to go so that new theme design is quick and efficient. To put the alpha version of this foundation theme to the test I used it to style Typograph from scratch.

Tabbed box navigation

When I created the new theme for Design is Philosophy I spent quite a bit of time developing and perfecting a JQuery and CSS based tabbed sidebar box that would contain navigation as well as other useful information for the visitor. For Typograph I further developed the tabbed box and isolated it in it’s own file to simplify customization for the user. It can also easily be deactivated by commenting out a single line of code in the sidebar.php template. The tabbed box contains navigation for pages and categories along with an about section, RSS link and search box by default. It takes standard WordPress tags and can be customized to include pretty much anything by editing the tabbedBox.php file found in the theme directory.

Download the Typograph theme from the WordPress Theme Directory here!

See a demo of the Typograph theme here

Categories
CSS Expression Web News WordPress as CMS

WordPress as CMS – The Project

I’ve been talking about this for a while now and it’s time I got a little more specific. It is my contention that with some small tweaks, WordPress can be used as an excellent Content Management System (CMS) and used to serve small-scale business websites. This isn’t something revolutionary – a simple Google search on the words “WordPress” and “CMS” gives you many interesting entries – but I don’t think the full potential of this alternate use has been explored. So I’ve taken it upon myself to see just how much I can get out of this small little program and if it can be used to serve my many clients in a more effective manner.

Why WordPress

That’s the first question I get: “Why WordPress? What’s the point? Why don’t you just use a CMS like Joomla! or Drupal?” To answer the last question first, in most cases using Joomla! or Drupal is like trying to kill an ant with a tank. Not only is the tool way too big and wasteful to do the job, but chances are the ant slips between the belt threads and you don’t actually achieve your objective at all. These huge Open Source CMSes are excellent if you are building large-scale community based websites with multiple blogs etc etc but for small business applications they are often too large and cumbersome. What’s needed is a simple, easy to understand CMS that gives the client the ability to quickly edit, update and manage her website with the least ammount of hassle. Sure, you can build something like that yourself, but why bother when there is already an application that pretty much does what you want available for free?

There are a couple of other reasons why I want to tap the full potential of WordPress for this project: First off, WordPress has an extensive and growing library of plug-ins and ad-ons that make it a very powerful piece of software. Seccondly, blogs have become an excellent way of promoting yuour business by letting your clients interact with you on a semi-informal basis. And WordPress is a blogging platform. Nuff said. Thirdly (and maybe most importantly), WordPress blogs has an uncanny ability to get synced up with search engines like Google and MSN almost immediately upon being launched. Through a couple of very interesting experiments I’ve learned that the best way to get your website listed on Google is simply to build it on a WordPress platform. And if you are running a business, geting listed on Google can be the difference between being noticed and going under.

Project Outline

What is needed to make this work? One major hurdle used to be the ability to put the standard blog front page on a sub page. This used to require quite a bit of coding, but in WordPress 2.3 and above it’s actually built into the main setup.

The next big issue is to get out of the standard header, body, footer layout scheme that all WordPress themes are built on. Although this feature is unneccesary in most cases, I can think of a dozen scenarios where you want individually styled pages with their own CSS backend and right now, that’s not something you can do right out of the box. I’ve been theorizing about this problem for some time and the solution appeared most unexpectantly at a session at MIX08 where the presenter to save time ignored the whole WP theme and built an external page with the loop calls inside it. It was a bit of an aha moment for me that you don’t actually need to stick to the rigid frame of WP, and although it is technically not correct to do so, if it makes my life easier, to hell with correctness.

Another question is to what extent one can use the Custom Fields to make styling changes in pages. I’d like to experiment and see just how far I can push this feature.

Finally, is it possible to make a non-WordPress site utilizing the WordPress infrastructure and database? In other words, can I build completely separate pages outside of WordPress and then use the loop calls etc to insert the required info in such a way that the site can be managed from the regular Admin panel without the client having any access to the controlling files. This final question is the crucial one because in the end what is needed is a manageable CMS that gives the client unlimited access to the content but limited or external access to styling, layout and other important files so that nothing can be “broken” by mistake.

The Future

In the coming weeks I’ll be launching two sites built on a WordPress as CMS v0.1 platform (pretty much stragith WordPress with some heavily customized themes) and once these are done I’ll dive head first into a major hacking project to see just how deep the rabbit hole goes. With any luck I’ll have a fully operational and customizeable CMS to use as a base for my client sites before the summer. In the spirit of cooperation I have every intention of blogging about all my findings and sharing the code and hacks with the online community. I’ll also blog further on how to modify WordPress blogs using Expression Web to help bring some beauty to the blogosphere.