You are Viewing : HomeBeginnerWordPress twenty ten Child theme – DIY tutorial

WordPress twenty ten Child theme – DIY tutorial

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

  1. Any basic text editor would do, Professional editors like Textmate/BBEdit (Mac) and Notepad++(windows) would accelerate the process.
  2. Some reasonable HTML, CSS language skills. And some knowledge on PHP.
  3. A latest browser. – Firefox or Chrome.
  4. 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.

1#childtheme_stylesheet

Create the child theme folder

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
*/
3#stylesheet_info 

Declaring the parent theme from child theme’s stylesheet

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.

2#activate_newtheme

Activate our new theme! Beginners, take a look at the highlighted information below the links.

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.

Google ChromeScreenSnapz004

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

filter_content_before

Filtering: inserting before wordpress post content

 

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

filter_content_after

Filter : insert content after post content in wordpress

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.

insert_ad_tut 

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.

FirefoxScreenSnapz001

Default output of twentyten_post_in()

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?

FirefoxScreenSnapz001

New output from our redeclared function twentyten_posted_in

 


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

  • http://www.chowchowbath.com Srikanth

    hey kavin,

    this is a very informative post. i was trying to make twenty ten more interesting on my blog but finally settled to one of blogohblogs themes. very detailed post and accruate in visuals. i ll come to back to read this further when i find time and lets see if i can implement what you have quoted.

    • http://kav.in kavin

      Thanks Srikanth, you’re always welcome, sir.

  • http://robcubbon.com/ Rob Cubbon

    Thanks for this very helpful post. I was able to add Adsense under the header (using wp_page_menu) and under the posts although it took some doing!

    It would be great if there was some visual guide to where the hooks are in Twenty Ten.

    • Anonymous

      Thanks, Rob. Twenty ten comes with a minimal set of hooks, that can be figured out easily by going through the functions.php. It serves as a great base to build upon the child themes.

  • http://www.bloomtofit.com Srdjan – Bloom to Fit

    Kavin, thanks for the great post. I’m having a little trouble with my Child Theme and was hoping you could help me out. I’ve uploaded and activated my child theme as instructed. However, when I go to make changes to the source code, such as stylesheet, I click on ‘update file’ and immediately get redirected to my homepage where I can see that no changes have taken place. Then I go back to my source code and see that the changes didn’t stick.

    What’s the issue? How can I get around this??

    Thanks! Srdjan

    • Kavin Gray

      Hai Srdjan, glad i could be of help. :)
      By “..source code”, do you mean the “Edit themes” section under appearance? If so, double check that your child theme is selected in top right corner in “select theme to edit”. It can range from a simple WP bug to file’s permissions that might be interfering with the save.

      Or you can try the FTP method, for example fileZilla – Login to server -> Proceed to the child directory -> Right click on the file -> View/Edit. This will open the file in your desktop’s editor(you can configure which though). After you make changes and save, switch to filezilla, it will now ask whether to update the file on the server. This is what i use daily, you will get a hang of it in no time :)

  • Doublezero7

    Thanks Kavin,
     it is a great tut you have here. 
    My problem though is that i created a child theme for my twenty ten theme but all i see in child them folder is a style sheet with almost no style at all, i understand it inherits from parent style sheet but i also don’t see files like function.php, header.php and the others so i dont know how to edit those folders. I want to add an ad banner just above the content area and have created a new widget but just dont know how to call the widget.

  • http://www.technotips.org/ Jayadrathsingh

    hi can you provide me the css for that author info below the post Thanks in advance!!

    • Kavin Gray

       Sure, just look at my style.css ( Search for #post-author-bio ).

  • http://www.technotips.org/ Jayadrathsingh

    I did that but the result is as below

  • http://www.technotips.org/ Jayadrathsingh

    I have managed the look like your author info but the rotating effect is not working

    • Kavin Gray

      Great! Make sure you include the rotate ( transform ) effect for all browsers.

      #post-author-avatar {
      -moz-transform: rotate(-15deg);
      -moz-transition: all 0.4s ease-in 0s;
      -webkit-transform: rotate(-15deg);
      -webkit-transition: all 0.4s ease-in 0s;
      -o-transform: rotate(-15deg);
      -o-transition: all 0.4s ease-in 0s;
      -ms-transform: rotate(-15deg);
      -ms-transition: all 0.4s ease-in 0s;
      transform: rotate(-15deg);
      transition: all 0.4s ease-in 0s;
      }

      • http://www.technotips.org/ Jayadrathsingh

        this is my code is there anything wrong?

        #author-avatar{float: left;
        margin: 10px -104px 10px 0;
        background: #F4F2F4;
        border: 1px solid #AAA;
        padding: 5px;
        padding-bottom: 15px;
        -moz-box-shadow : 1px 1px 0 #FFF inset, -1px -1px 0 #FFF inset, 0 3px 8px #999;
        -webkit-box-shadow : 1px 1px 0 #FFF inset, -1px -1px 0 #FFF inset, 0 3px 8px #999;
        -o-box-shadow : 1px 1px 0 #FFF inset, -1px -1px 0 #FFF inset, 0 3px 8px #999;
        box-shadow : 1px 1px 0 #FFF inset, -1px -1px 0 #FFF inset, 0 3px 8px #999;
        -moz-transform : rotate( -15deg );
        -webkit-transform : rotate( -15deg );
        -o-transform : rotate( -15deg );
        -moz-transition : all 0.4s ease-in;
        -webkit-transition : all 0.4s ease-in;
        -o-transition : all 0.4s ease-in;}

        #author-avatar:hover {
        -moz-transform : rotate( 0deg );
        -webkit-transform : rotate( 0deg );
        -o-transform : rotate( 0deg );
        -moz-transition : all 0.2s ease-out;
        -webkit-transition : all 0.2s ease-out;
        -o-transition : all 0.2s ease-out;
        }

        #author-avatar img {
        }
        #author-avatar img:hover {
        }

        • Kavin Gray

          Looks fine. Please make sure browser cache is not playing tricks here or no missing commas/semicolons.

        • http://www.technotips.org/ Jayadrathsingh

          os it true 
          box-shadow : 1px 1px 0 #FFF inset, -1px -1px 0 #FFF inset, 0 3px 8px #999;

          or this (have t0 add – before it)

           -box-shadow : 1px 1px 0 #FFF inset, -1px -1px 0 #FFF inset, 0 3px 8px #999;

          and 
          transform: rotate(-15deg);  transition: all 0.4s ease-in 0s;} 

          as  -transform: rotate(-15deg);  
          -transition: all 0.4s ease-in 0s;}

        • Kavin Gray

          Nope not needed. It’s the standard one, doesn’t need prefix or hyphen in front. Share the link to the page, if possible.

        • http://www.technotips.org/ Jayadrathsingh
        • Kavin Gray

          Selector issues. Remove the prefix #entry-author-content on line 532, or add the selector to the hover rule too ( as in below example).

          http://pastebin.com/6AYgDMGk

        • http://www.technotips.org/ Jayadrathsingh

          thanks a ton bro!!! your are awesome!!! 

        • Kavin Gray

          You’re welcome bro, glad I’ve been of help!