Every WordPress blogger out there might definitely agree that no theme out of the box absolutely fits his/her personal preferences. A well created child theme can inherit the robustness and bring uniqueness to your blog. Recently I made a twenty ten child theme for my friend-cum-client which he warmly approved, and then he asked, “How do I add a post slider?”. I thought an article about child theme should not end with creating one, but by adding more features and bringing it out unique.
I used the twenty ten theme as the parent theme for multiple reasons, two below.
1. Semantic HTML5-compatible markup.
2. Default theme, so virtually in every wordpress installation.
Why a child theme
- Easiness – new style.css file is the only requirement for the child theme.
- Maintenance – Child theme is safe from parent theme’s update process.
- Customization – Change the parent theme’s code without touching it. If theme offers multiple hooks, the process is even simpler.
Entire guide assumes that you have a local server installed on your computer. This is the safest, fastest, and easiest and portable way to work with. If you don’t have one, know how to install in PC or Mac .
Tools
- Any basic text editor would do, Professional editors like Textmate/BBEdit (Mac) and Notepad++(windows) would accelerate the process.
- Some reasonable HTML, CSS language skills. And some knowledge on PHP.
- A latest browser. – Firefox or Chrome.
- Debugging tools – These can be extremely helpful on fixing annoying errors. Get one for your browser.
- Firebug for firefox.
- Chrome comes with built in Console. Right click anywhere and select inspect element.
- Safari, Enable developer tools from advanced preferences.
- Dragonfly , if you swear by Opera. Right click anywhere and select inspect element.
- Internet explorer? It is the best browser for downloading one of the better browsers listed above. No? okay, get IE9 and click F12 .
Magic of Style.css
Let’s choose a name for the child theme. For e.g. I chose Ashten.
Browse to your wordpress themes folder(it’s in /path/to/wordpress/wp-content/themes/). Locate the folder twentyten. Now, create a parallel folder with the name we chose.
Create a file style.css, that will be our child theme’s main style sheet.
Now copy the code below to the above file. This is the file header, enclosed within comments, located at start, that wordpress acquires theme details. Two important fields would be Child theme’s name( any valid name, except twentyten) and parent theme(template)’s name. Please refer with the image below.
/* Theme Name: Ashten Theme URI: http://kav.in/ Description: Dashy twenty ten. Author: Kavin Author URI: http://kav.in Template: twentyten Version: 0.1 */
Replace the values to Theme name, Theme URI, Author, Author URI to your liking. Essential line here is the Template: twentyten. WordPress, now will use twentyten’s files as the template.
Now proceed to the admin section of your blog. The new theme is shown as the option, like below. “Activate” the new theme.
Now reload the viewer facing side of your blog and take a look. An un-styled page appears. Why so? Because defining the parent theme auto-inherits only the code (functions, variables etc.) and Not the styles, unless explicitly imported. This is very useful, IMHO.
Now you’ve got two options. One, if you are fluent in CSS, you can start styling the theme from scratch. Second, start by importing the parent theme’s stylesheet and overriding theme’s styles there after. Let’s choose option 1, for now.
/**
* "../" points to the directory above. “../twentyten”, a folder in
* the above directory.
* @import url - Import function of the CSS. Accepts path or
* URL. Be careful with the CaSE sensitivity though.
*/
@import url("../twentyten/style.css");
/**
* Let us make sure that child theme is being loaded.
*/
body {
background: skyblue;
}
Now reload the page. Child theme bears no difference to twenty ten, except for the background we modified, skyblue.
Our child theme, just like twenty ten, but with a skyblue background.
Now we shall proceed to next step.
Modifying the parent theme’s output from the child theme
Child theme can modify the parent theme’s code indirectly by altering the output.
It always helps a beginning developer to study the code and the documentation if available. Almost everything else can be figured out with Google. Excellent manual on PHP can be found at php.net, WordPress documentation can be found at wordpress codex.
Inside the child theme’s folder, create a file named “functions.php”. you can refer about functions.php at codex here.
Open the twentyten’s files (as required and when noted) alongside, as that helps to understand the process better. We are not touching the parent theme, it’s for reference purposes only.
Modifying the code can be done with
- Hooks – Filter and action hooks. (both have add_ and remove_ functions)
- Redeclaring the over-writable functions on Parent theme’s code.
- Alternative template files on child theme’s folder.
Hooks
WordPress offers two type of hooks – Action and filter. Action hooks are fired at specific points, or when an event occurs. Filters hooks – are used to modify input and output. Both type of hooks act similarly. Now, it’s time for some examples – way these are better understood.
Example:. Filtering post content
Say for example, we need to insert some text or image into the post. Each wordpress post’s content is output with the_content() function/hook. Like most wordpress functions, the_content() can be hooked and filtered.
Now let’s create a new function, which gets the input, and outputs the modified input. Then we attach the function to the_content() .
Example , Add something above content.
code
// Insert something before the post.
add_filter( 'the_content', 'filter_content_before');
function filter_content_before( $input ) {
// returns the output.
// . is php concatenation operator.
return "<b>Hello all</b>, " . $input;
} // END function filter_content_before
Result
Example – Adding something below post content.
code
// Insert something after the post.
add_filter( 'the_content', 'filter_content_after', 11);
function filter_content_after( $input ) {
return $input . "Regards,<br />Yours admin!<br />";
} // END function filter_content_after
// Insert something after the post, but before previous one.
add_filter( 'the_content', 'filter_content_right_after', 10);
function filter_content_right_after( $input ) {
return $input . '<hr style="background: skyblue; height: 4px;">';
} // END function filter_content_right_after.
Let’s take a look at the above code. By default, functions are hooked in the order they are added to the filter.
So far , filter_content_right_after() appears after filter_content_after() . Say, we want that to appear right after. Here comes the hook priority, the third argument to add_filter.
Lesser the number, Higher the priority.
Greater the number , lesser the priority.
So, function with priority number 1 would be executed long before function with priority number 12. That said, the filter_content_right_after() “10″ has a higher priority than filter_content_after() “11″. Hook’s priority are similar to CSS rules priority, later ones have higher priority(Cascading). If both our functions had priority 10, then they are executed in the order of attachment.
Result
This is most commonly applied to show up Advertisements at the top or bottom of the posts. Want to add something at specific points in every post? Here’s how.
code
/**
* Insert something into the post, for example ads.
*/
add_filter( 'the_content', 'insert_between_moi_posts' );
function insert_between_moi_posts( $content ) {
// Insert this.
$insert_this = '<p><a href="http://example.com"><img src="' . get_bloginfo( 'template_url') .'/images/ad_banner.gif" /> </a></p>';
// Insert in place of our placeholder <!--ad-inserts-->
$content = preg_replace( '/<!--ad-inserts-->/im', $insert_this, $content);
// always return the content, post will be empty failing to do so.
return $content;
}
- <!–ad-inserts–> is our placeholder. It can also be {ad-inserts} , but using html comments is more safe.
- The content, here an image, will replace the <!–ad-inserts–> , wherever it occurs in posts.
- we use php function preg_replace, which replaces our placeholder wherever it occurs inside posts. Learn more about preg_replace.
- Now edit any post in wordpress admin, go to HTML mode, insert <!–ad-inserts–> anywhere and view the post on the blog. Now it should be replaced with an image.
Example below.
Inserting custom content in between posts Above, the placeholder insert and below, the replacement image that appears.
Overriding functions
Not every function can be over-ridden. Trying to redefine an already existing function with the same name will throw up an error – Fatal Error: Cannot re declare function_name (previously declared in line number..) .
A Parent theme’s functions if enclosed within the if( ! function_exists ) php conditional, can be overridden. Take the below function from twentyten, which you can find in functions.php inside twentyten folder.
if ( ! function_exists( 'twentyten_posted_in' ) ) {
function twentyten_posted_in() {
// Retrieves tag list of current post, separated by commas.
$tag_list = get_the_tag_list( '', ', ' );
if ( $tag_list ) {
$posted_in = __( 'This entry was posted in %1$s and tagged %2$s. Bookmark the permalink.', 'twentyten' );
} elseif ( is_object_in_taxonomy( get_post_type(), 'category' ) ) {
$posted_in = __( 'This entry was posted in %1$s. Bookmark the permalink.', 'twentyten' );
} else {
$posted_in = __( 'Bookmark the permalink.', 'twentyten' );
}
// Prints the string, replacing the placeholders.
printf(
$posted_in,
get_the_category_list( ', ' ),
$tag_list,
get_permalink(),
the_title_attribute( 'echo=0' )
);
} // END function twentyten_posted_in.
} // END if !function_exists check.
Above function is declared only, if no other function by the same name exists. This function is used to output the information about, and below the post on single view.
Now, let’s say, we would like to have the post meta information as a list rather than continuous lines. So let’s re-declare the function twentyten_posted_in.
function twentyten_posted_in() {
// Prepare the links.
$tag_link = get_the_tag_list('Tags: ',', ','');
$cats_link = get_the_category_list( ' , ' );
$author_link = '<a href="'. get_author_posts_url( get_the_author_meta( 'ID' )) .'" title="View more posts by '. get_the_author() .'">'. get_the_author() . '</a>';
$edit_post_link = '<a href="' . get_edit_post_link($post->ID) . '">' . __('Edit.', 'kavin') . '</a>';
$post_meta = '';
// Enclosing div.
$post_meta .= '<div class="post-meta-foot">';
// Avatar
$post_meta .= '<div class="post-author-avatar">';
$post_meta .= get_avatar( get_the_author_meta('user_email'), 72);
$post_meta .= '</div><!-- end #post-author-avatar -->';
// Post details.
$post_meta .= '<ul class="post-meta-list">';
// Author name and posts URL
$post_meta .= '<li>Posted by : ' . $author_link . '';
// List categories
$post_meta .= '<li>Categories : ' . $cats_link . '';
// List tags.
if ( $tag_link )
$post_meta .= '<li>' . $tag_link . '';
// Permalink.
$post_meta .= '<li>Bookmark : <a title="Permalink to ' . the_title_attribute( 'echo=0' ) . '" href="'. get_permalink() . '" rel="bookmark">Permanent Link</a>';
// Edit post
if ( current_user_can('edit_post') )
$post_meta .= '<li>Manage : ' . $edit_post_link . '';
$post_meta .= '<ul>';
$post_meta .= '</ul></li></ul></div><!-- end class post_meta-foot -->';
echo apply_filters( 'twentyten_posted_in', $post_meta);
} // END function twentyten_posted_in
After some minimal styling, it appears as below. Cool, isn’t it?
Overriding with alternate files (namesakes)
Template files, for example -
- header.php
- footer.php
- loop.php
- sidebar.php
- anything.php except index.php(unless wp 3.0 or newer)
will be over ridden, when a file with exact same name as the original parent file is present in the child theme dir. For example, to replace header.php, put your own header.php in child theme’s folder. Also, it’s better to copy the header.php from parent theme( here twenty ten), to child theme’s folder (here ashten) and then proceed with modifications. This way we can make sure we steer safe from messed up HTML tags.
Styling the Child theme
As told earlier, css styling can be done either from scratch, or after using @import url(“../twentyten/style.css”);. (Google’s page speed advises to avoid CSS @import, in such case, simply copy the code to the child). Child theme’s styles will override the parent theme’s styles as they occur later ( CSS cascading – later rules have higher priority ).
Next post on this series will be on adding various dropdown menu solutions and then fancy post sliders will follow.
Cheerio,
Kavin