
In this article, I am going to go over the rest of the files in the Designredux WordPress theme before we go on to adding extra features, scripts, and custom pages to the theme. Check out How to Disassemble a Free WordPress Theme Part 1 if you missed it.
The files that this article is covering are comments.php, single.php, functions.php, and style.css.
Comments.php

The comments contains everything required for the comments to function. This includes the comments itself, the comments form, and various checks that do different things depending on the settings set in WordPress.
1. Some pre-flight checks
if ('comments.php' == basename($_SERVER['SCRIPT_FILENAME']))
die ('Please do not load this page directly. Thanks!');
Checks to see if the comments.php is loaded directly into the browser. If it is being directly loaded, it will stop loading and display the message within the die() function. Comments don’t work outside of the WordPress Loop so it would be pointless to load it directly.
if (!empty($post->post_password)) { // if there's a password
if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password) { // and it doesn't match the cookie
<p class="nocomments">This post is password protected. Enter the password to view comments.<p>
<?php return; }}?>
Checks to see if a password is set for the post. If a password is set, it will stop the post from being displayed and instead display an input box where you can enter a password in order to see the post.
<?php if ($comments) :?> <ol id="comments_list">
<?php $comment_index = '1'?>
<?php foreach ($comments as $comment) : ?>
//fun stuff inside foreach loop
<?php endforeach; ?>
Checks to see if there are comments before it begins the process of churning out all the comments. Then it sets $comment_index = ‘1′ in order to be used later for displaying the comment’s number. Only after all that does it begins the foreach loop which will go through every comment one by one and do everything inside the loop.
2. Inside the comment’s foreach loop
<?php $comment_type = get_comment_type(); ?>
<?php if ($comment_type == 'comment') { ?>
//fun stuff
<?php } else { $trackback = true; } ?>
The first line gets what type of comment it is. There are three types of comments you can get. The three being regular comments, trackbacks, and pings. The reason for checking this is to separate the comments from the trackbacks and pings so it can be organized better. After getting the type, it checks to see if it is a regular comment. If it is a regular comment, then it does all the fun stuff after that. But if it is not a regular comment, it just sets $trackback to true, which tells us that there are trackbacks/pings in this post.
<li class="<?php if (1 == $comment->user_id) { ?>comments_author <?php }; ?>
<?php if ($comment_index % 2 == 1) { ?>odd<?php }; ?>" id="comment-<?php comment_ID() ?>">
The first line checks to see if the commenter is an author by checking to see if its user id is equal to 1. If it is then it adds the class “comments_author” to the <li> tag so it can be styled differently from the other comments. The second line checks to see if the comment’s number for that comment is odd, if it is then it will add a class of “odd” so it can be styled differently from the even comments for easier reading. <?php comment_ID; ?> just adds the id for the comment.
<span class="comments_index"><?php printf("%03d", $comment_index); $comment_index++; ?></span>
The printf() function is used to format the comment’s number for display. The format in this case being defined by “%03d”, which just means it has to be outputted as 3 digits and if it isn’t already in 3 digits format then add leading zeros until you get 3 digits. That is why it comes out as 001 and 002 instead of 1 and 2. $comment_index++ just adds one more to the index so the next one will be 2, 3, 4, etc.
<?php if ($comment->comment_approved == '0') : ?> <em>Your comment is awaiting moderation.</em> <?php endif; ?>
The first line checks to see if you have set comments to be approved before displaying in the settings of WordPress. If you have it set to be approved first, then it will just give a message to the commenter that it is awaiting moderation.
3. Trackbacks and pings
<?php if ($trackback == true) { ?> <h3>Trackbacks</h3>
<ul id="tracksbacks">
<?php foreach ($comments as $comment) : ?>
<?php $comment_type = get_comment_type(); ?>
<?php if($comment_type != 'comment') {?>
<li>
<?php comment_author_link(); ?>
</li>
<?php } ?>
<?php endforeach; ?>
</ul>
<?php } ?>
The first line checks to see if there are any trackbacks or pings. If there is, then it will display them by using a foreach loop again. This is pretty straightforward after having gone through the comment’s foreach loop. This time you just display a link to the trackback/ping if they are not regular comments.
4. If there are no comments
<?php else : ?>
<?php if ('open' == $post->comment_status) : ?>
<?php else : // comments are closed ?>
<p class="nocomments">Comments are closed.</p>
<?php endif; ?>
<?php endif; ?>
If there are no comments for this post, it will do what is after the <?php else: ?> and before <?php endif; ?>. The second line pretty much just checks to see the status of the comments. If the comments are open, but there are no comments it doesn’t do anything. But if the comments are closed it will say so.
5. Pre-flight checks before displaying the comments form
<?php if ('open' == $post->comment_status) : ?>
<?php if ( get_option('comment_registration') && !$user_ID ) : ?>
<p>You must be <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?redirect_to=<?php the_permalink(); ?>">logged in</a> to post a comment.</p>
<?php else : ?>
Before we can display the comments form, we have to check if the comments are open or not and that is what the first line does. Now if it is open, but the settings in WordPress is set so that only registered users can comment then it will force you to login if you haven’t already done so. If all the conditions are satisfied, the conditions being comments are open and you are logged in if required to do so, then the comments form will be displayed.
6. Comments form
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
Sets the action of the form to the wp-comments-post.php file, which will process the form.
<?php if ( $user_ID ) : ?> <p class="comment_status">Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Logout »</a></p>
<?php else : ?>
Checks to see if you are logged in. If you are logged in, it will tell you so and also give you an option to log out if you want to.
<label for="author">Name <span><?php if ($req) echo "*"; ?></span></label> <input type="text" name="author" id="author" class="text" value="<?php echo $comment_author; ?>" size="22" tabindex="1" />
<?php if ($req) echo “*”; ?> checks to see if the settings in WordPress is set so that it requires the user to fill out their name and e-mail. If it does require it, then it will display * next to the field. <?php echo $comment_author; ?> fills in the user’s name if they are registered, but if they are not, it just leaves it empty.
<?php do_action('comment_form', $post->ID); ?>
The do_action(’comment_form’, $post->ID) function is a hook for plugins, similar to wp_head() in the header. So don’t go deleting this or comment plugins won’t work.
Single.php

The single.php is used to display single posts. In this theme it is identical to index.php, except for a couple of things. For one, the number of comments are no longer displayed in the top right. And secondly, the comments.php is called on this page.
1. Comments.php
<?php comments_template(); ?>
<?php comments_template(); ?> calls the comments.php file and spits it out. That’s it.
Functions.php

The functions.php file is used to hold all the custom functions outside of what WordPress offers that you plan to use in your theme. In this theme, it just contains the WP-PageNavi plugin, which is used in the theme for easier pagination.
Style.css

The style.css file is what WordPress expects to be your main stylesheet for your theme. It also contains nifty information about the theme that WordPress uses to display. Breaking down the style.css file is out of the scope of this series.
1. General information about the theme
/* Theme Name: designredux Theme URI: http://www.blogdesignblog.com/themes/ Description: A simple sweet blue/silver theme designed by blogdesignblog.com Tags: Blue, fixed width, widgets, two columns, silver Author: Vinh Le Author URI: http://www.blogdesignblog.com Version: 0.1 . This theme is distributed under the Creative Commons Attribution-Noncommercial 3.0 Unported License. Basically you can do whatever you want with it as long as you credit me with a link and use it for non-commercial purposes. A link/credit is already integrated on the bottom of the footer, you can remove it, but only if you put it somewhere else on the page. . */
This is pretty self-explanatory. It is just basic information about the theme.
2. Color Scheme
/* `Color Scheme ----------------------------------------------------------------------------------------------------*//* Blue : #6f9fbd Text: #42423d Black: #464646 Deep Black: #272727 Silver: #eeeeee Pink: #ec81c0 */
This is usually not required, but I thought it would make life easier for people who want to customize the theme.
Conclusion
This concludes the second part of this article. Now that we are done disassembling the WordPress theme, we can actually start the really fun part, which is modifying the theme to do what we want. This includes creating custom pages, scripts, and plugins. If there is something specific that you would like to see added to the theme, just leave a comment and I will cover it in a future article.
Subscribe today by RSS for free and get more great blog design tips and lists. If you don’t know about rss feeds or you want to use the email subscription option, read this page on subscribing to Blog Design Blog.
Further Reading
1. WordPress Codex for Theme Development.
References
1. Top picture is by wasabicube




69 comments
Thankfully, WordPress 2.7 is going to make the comment template file a lot less cluttered. It does bring up the issue of backward compatibility, but I’ll take what I can get
Hi, I would like to know how you make those snippets of code show up like that in your blog posts. Is it a plugin or something?
Hi, I really like how you’re getting under the bonnet of a WP theme like this. It’s a different take on understanding the code and what it can do. I will be bookmarking these posts.
Thanks a lot! I love any post that disassembles a WordPress theme.
Great tutorial in tuning your wordpress themes
Thanks lots
Great infomartion…
Superb work.
Very usefull
Thanks
Great work, webmaster, nice design!.
I am from South and too poorly know English, please tell me right I wrote the following sentence: “A description of problems commonly seen in undergraduate and recent graduate resumes and how to fix them.”
Regards
Nadav.
В нынешней ситуации большинство тем отходят на второй план. Интересно, как мы будем жить, если доллар рухнет?
Кризис, говорят, в марте усилится. Хотелось бы знать, кто затеял все это
и как вообще мы докатились до такой жизни.
Thank for the convenience
Прикольная статья, но хотелось бы поподробнее узнать о некоторых моментах… Как можно с Вами связаться?
Thank you for taking the time to break down a wordpress (WP) theme for us. I’m trying to launch a web design company and I’m pretty comfortable coding websites using css. I took a class at a local college and they turned me onto WP and it’s potential. I’m a total convert to the power of what WP can do if you get creative with it. My goal is to be able to build sites that integrate WP seamlessly into an existing site. That site could be a conventional HTML site but with some pages built using WP or built entirely out of WP. Because I’m designing a site from scratch and integrating WP into it I need to build a theme from scratch too and not tweak an existing theme. My problem is I can’t find resources that explain how to control with css some of the php code WP uses. Case in point, I’m currently bogged down trying to figure out how operates. It generates a lot of code but I can’t figure out how to control it with css. I would love to see you or someone else talk about how to design the php code and not just what it does.
My website I’m building right now is a good example of an integrated site where only the about page is built out of WP. And it’s also where I’m trying to figure out how to design my comments.
Thanks for all the great posts on your site I’ve read so far.
In the post above it wouldn’t display the code I pasted in it so here is the php code that is perplexing me:
wp_list_comments
Дизайн у Вас интересный, я вот тоже для блога искал - стала прикручивать, а все посты куда то делись. Эээх… буду писать заново
А как на вашу рсс-ленту подписаться? что то не пойму
Thanks for your Work kind words by abra
действие, служба, предпринимательство, экономическая деятельный, нап равленная на достижение определенных результатов (получение прибыли). - сделки, торговые операции. - деловая житье, деловые круги, экономическая деятельность вообще вотличие от других сфер жизнедеятельности (культуры, политики, образова ния и т.д.). - компания, предприятие, экономический субъект. Имя, обозначающийучреждение, специализирующееся в той или иной области предпринима тельства.
Дисбазия - (дис + греч. foundation - ходьба, выступка). Нарушения ходьбы, походки.
Thanks for sharing the information about disassemble information about word press theme
Thanks for putting you valuable input regarding disassemble wordpress themes
Privet Vsem! Normalniy sait/ Ostavlyayu oztziv.
Tak, komu interesno: http://dori-v-top.mylivepage.ru
tesekkurler…
Hello. Nice guest. see my comment
http://www.armiya.tainafamilies.ru/hyves73.html
I really like, thanks!
Heloo!!!!!
See my comments
http://www.famalydoc.ru - Vse o Familii
Heloo!!!!!
See my comments
http://www.kinoimperiya.ru -Tolko Luchshie filmi
Блин, только что хотел это сказать.
They can be difficult to create and maintain. ,
Класс добавил в избранное!
The nineteenth century saw the benefits of one money throughout the civilized world. ,
Спасибо конечно … но …
Great Blog very useful to all webdesigners, I suggest all designer to share this blog
Nice resources, Thanks
Спасибо
Спасибо. А для графического наполнения Вы материал где находите? Меня всегда интересовало, как получается научиться разыскивать на каталогах фоток настолько классный материал… В поиске море всякого отображается, а чтобы увидеть реально что-то классное - дык на это нужно пол дня, а то и день потерять…. Или это Вы из личной коллекции взяли?
Спасибо за пост.
Спасибо очень интересно!
Привет! С удовольствием почитал Ваш блог. Хочу также поздравить Вас и всех читателей этого блога с новым 2010 годом. Удачи всем, новых жизненных побед и исполнения всех ваших замыслов.
Really Gr8 Effort
C наступающим Вас! Пусть Ваши мечты сбудутся!
Да, таких интересных блогов я невидел! Этот блог даст фору многим сайтам ( по содержанию и не только)! Пять с плюсом баллов!
Уважаемые читатели. С Рождеством христовым хочется вас поздравить. Админу сайта отдельное пожелание-побольше читателей на блоге, креативных интересных статей и всего всего всего
Really great stuff… i was lloking for same….
very nicely done!!!
Hello, I found your blog from yahoo and read a few of your other posts.They are awesome. Please keep it up!
I really appreciate the effort you have given to this post. I am looking forward for your next post. I found this informative and interesting blog. I just hope you could make another post related to this. This is definitely worth reading.
very nice site
i really love your site dude
Thanks for sharing, beautiful content and great post.. Really help!!!!
I would like to say a thanks to your for the post that you have shared with us, I ll recommend it to all the visitors of the blog , its worth reading…..
Thanks for putting you valuable input regarding disassemble wordpress themes.
Great post, still applies nowadays.
Find a best gift boxes here , thanks.
Best keychains online for you , don’t wait to get it.
А как на вашу рсс-ленту подписаться? что то не пойму
Thanks for another in-depth post. I read part 1 and really enjoyed it and this post is really good too. I’ve bookmarked both so I can come back and read over these again. Thanks again.
Thanks for writing. was a really nice article. I always follow site. More waiting…..
I would like to say a thanks to your for the post that you have shared with us, I ll recommend it to all the visitors of the blog , its worth reading…..
Nice explanation.
Thank you.
very useful for me, thanks for share your article with me……
Very nice and descriptive post you have shared. everyone can understand the steps your have mentioned. Thanks for sharing..
As I said about your other articles as well, this one is also a good one. I just love your style of explaining. It’s very intuitive!
yes very helpful thanks, I have used wordpress many times and strugled trying to modify it, If I cna get it to work with my angular cheilitis project I might implement it,
This really helps to focus down on what your blog really needs. Thank you for showing the actual nitty gritty and not just the fluff.
So much to learn about Wordpress and backlinks. Thanks for the tips and info. I shall incorporate this into future work.
Nice effort, very informative, this will help me to complete my task.
I suggest all designer to share this blog
Thats a great post. Thanks for that information about disassemble.
Jane
Pro designers will really improve that kind of thing.
Todd
Add a comment