WP Theme Lesson #5: The Loop

tutorial-series.gif The Loop calls for your blog’s entries. It’s the most important set of PHP codes. By now, you should already know what to do before this lesson, of my tutorial series, begin. Go ahead and do that first, then let’s review what we’ve learned so far.

So far, you’ve learned:

Let’s start with lesson #5:
By now, you should have opened Xampp Control, the “tutorial” theme’s folder, browser at http://localhost/wordpress, and the index.php file in notepad.

This is what you should have in the index.php file:

indexphp.gif

Remember, to learn these codes or mumbo jumpo, type everything, DO NOT copy and paste.

Step 1:
Add a DIV (invisible box) under the header area. Give it “container” for ID, like this:

<div id=”container”>

</div>

What is this DIV for? It’s for separating your content from everything else that comes after it, stuff like the sidebar and footer.

Step 2: Add the following codes between the Container DIV tags. Try to type this out exactly like you see it. If you get any errors, retype it.

<?php if(have_posts()) : ?><?php while(have_posts()) : the_post(); ?>

<?php endwhile; ?>

<?php endif; ?>

From this point on, it’ll be easier for you to recognize what each set of codes does instead of what they are and how they work. What you just typed is The Loop in WordPress. Before I explain what those codes are in words. You should have this:

the-loop.gif

Notice that I indented every line within the content box and I tend to skip a line a lot. That is for organization. It’s not enough to type the codes. You need to organize them so, later on, you know where everything is and which set of codes are related. For the indents, use tabs instead of spacebars.

What just happened?

  • if(have_posts()) – checks to see if you have any post.
  • while(have_posts()) – if you do have it, while you have any post, execute the_post().
  • the_post() – call for the posts to be displayed.
  • endwhile; – sticking to rule #1, this is to close while()
  • endif; – close if()
  • Note: not every set of codes need two parts in order to open and close itself. Some can self close, which explains have_posts() and the_post();. Because the_post(); sits outside of if() and while(), it needs its own semicolon to end/close itself.

Step 3: In previous lessons, you learned how to call for your blog’s title by using bloginfo(‘name’). Now, you learn how to call for the post titles in between The Loop.

Type <?php the_title(); ?> after the_post(); ?> and before <?php endwhile; ?>

the-title.gif

Save the index.php file, refresh your browser. You should see Hello World beneath your blog’s description. By default, your blog has only one post. For me, my test blog has multiple posts so I have multiple post titles. And because the post titles I used are the same and aren’t organized at this part of the tutorial, it looks like one long line of Hello World.

hello-world.gif

Step 4: Turning your post titles into post title links. Remember how you turned the blog title into a link? Same thing here, add <a href=”#”> and </a> around <?php the_title(); ?>

Save index.php and refresh browser. Now your titles are title links, but they point to nowhere. To make each title point to the right post. You need to replace the pound sign # with the_permalink().

<a href=”<?php the_permalink(); ?>“><?php the_title(); ?></a>

the_permalink() is the PHP function that calls for the address or location of each post. Save and refresh the browser. If you have only one Hello World title, hover over that link, look at the status bar, at the bottom of your browser; it’s no longer http://localhost/wordpress/#.

If you have more than one title link, you’ll see that each title links to a different post or web page. But, our post title links are still on the same line. To separate them, add the <h2> and </h2> tags around your link codes.

<h2><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></h2>

Remember H1 that we used for the blog title? That’s your web page’s heading. H2 is used for sub-headings. Now that your title links are sub-headings, each gets its own line. Save index.php and refresh the browser to see the change.

post-title-heading.gif

This is the end of this lesson. You should now have:
end-lesson-5.gif

Note: If you haven’t already, make several dummy posts to test your theme. Go to http://localhost/wordpress/wp-login.php. Login, click on the Write tab, make sure you’re looking at Write Post, make a post, then do it several more times. You can title them all Hello World like I did or give them unique titles.

Follow this WordPress Theme Tutorial Series from the beginning.

What's Next?

so i made it to your site via a google search. this isnt quite the right place to post this comment, but what the heck…

i am in the process of searching for good website designers specifically with wordpress. i want to do an integrated site, where my blog IS my website.

im dangerous enough to install wordpress on a hosting account, upload a theme, etc., but not much more than that.

any ideas of top quality design firms with LOTS of wordpress/blog/SEO experience that will work with a small potato like me?

my meager blogging skills and site are on display at:
http://www.trihomewiz.com/blog
(my new site will be a new domain)

Small Potato:

Sorry, I haven’t rubbed elbows with other wordpress designers. Don’t know who to suggest.

do you do design work? how are you getting to that $1M goal ;) ??

Hi Small Potato,

J.R. from seedsforwealth, I did a review of your site a little while back.

I installed your Digg 3 Columns on one of my sites and I was trying to add more pages to be displayed at the top, beside Home and About. Except the pages won’t get added.

The pages are added in my sidebar but I want it prominently displayed along the top. I checked the code in theme editor but before I mess it up cutting and pasting, I thought I’d ask you first.

I know you’re busy, but I have to ask. Could you make the theme add pages to the top automatically? It’s a really great template and I don’t want to change it to something else, Its exactly what I want for my new site.

Thank you so much,
J.R.

Small Potato:

J.R.

Open the obar.php file. Find wp_list_pages(), copy and paste that line to replace the about link in the header. Replace it completely, including the LI tags surrounding to the About link.

Change depth=3 to 1
For title_li, delete the h2 tags and word “Pages”

Small Potato:

@Rama – I did do design work. I’m taking a break. I doubt that freelancing will take me to a million ;)

Wow SP, that was painless. Thank you again. :D

Hey nice tutorial I am following it along but ive got a problem here.

I have typed out the code exactly and check it however I don’t see the Title post.

Before anyone asks Yes I do have a post lol.

Thanks for any help and keep up the tutorial.

Ahh the code did not paste in… anyway I can dump it for you to access and see what I have done wrong?

Ok I have just removed the ?php from the start to see if that works I did have the ?php correct :)

Nope sorry for the comment spam. I have uploaded my code here.

http://the1qwerty.com/dev/learn/index.txt

sorry for the problems.

Ahh nvm I worked out my problem I forgot to close the div id”content” up sorry for this what could be considered spam But I am just trying to fix my problems.

Small Potato:

That’s ok Qwerty. In the beginning, it’s tricky to keep track of everything. I’m glad you worked it out. Now go to the next tutorial! I kid I kid. Any more problem, just ask. It’s not comment spam.

[...] copy everything in the index.php file, paste it in the 404.php file, and then remove everything of The Loop, except for the Not Found area (after Else of The [...]

you make it look so simple, seems like i have to memorize it, but i put the site and tutorial on bookmark :)

I’m using WOS Portable and Notepad+++ for editing. When I try the bloginfo(‘url’) call, it is pulling localhost/wordpress/localhost/wordpress instead of going straight to the wordpress index page. Any ideas what is wrong?

Regards,

MLO

check the full url, are you adding another set of “localhost/wordpress” in front of bloginfo(‘url’) ?

Hi:

Hi,
just wanted to tell you that you’ve got a new fan – after about 3 weeks of staring at the wordpress codex I’ve started following tis course and I think its terrific)
Hope to modify some of your themes in due course or even – god forbid, create my own..

Ok, it’s been about 40 minutes, I’ve started from lesson one up to here.. Every thing has gone smoothly.. You explain every thing quite clearly. Time to have a break and make a tea or some thing.. then I will come back and resume – on to lesson 5a/6 :)

No problems following along.. you gonna make me a div luvva? cuz I am used to table tr td
nada

Adana:

Hello Small Potato. Do you recommend putting post heading into a div ,say, . If I do so , may it cause problems in the future?
Thanks in advance.

It’s better to put it in h2 tags. Div is a better fix if used for sidebar headings, but don’t make that fix if you don’t know how to change it through the functions.php file. Widget default structure for sidebar headings are h2 tags, not div.

Joe:

Hello, and thanks for your work. I’m training to fallow this tutorial. At the beginning everything was ok, but at the end of WP Theme Lesson #5: The Loop, don’t work properly (visualization and links). When I try to charge again the tutorial theme the browser tells me this:
Warning: Cannot modify header information – headers already sent by (output started at C:\wamp\www\titulares\wp-content\themes\281\functions.php:11) in C:\wamp\www\titulares\wp-includes\pluggable.php on line 331
When reload the page, I don’t see the content properly and links don’t work.
I see that:
�>TITULARES
TITULARES
Una casa se viene a bajo

�>TITULARES
This header link to:
Not Found
The requested URL /titulares/� was not found on this server.

TITULARES
This show a repetition of the header, not the proper sentence.

Una casa se viene a bajo
This link to:
Forbidden
You don’t have permission to access /titulares/�http://localhost/titulares/ on this server.
This is what I don’t see:
TITULARES
cocoloco
Una casa se vine a bajo
And others posts I have
I have checked my syntax reading again; and after by copy and paste from your page. It is this my last attempt to do it by myself? Or there is a solution for me?

Joe – Don’t copy and paste. Do this lesson over again. If you have other problems, bring it to my forums and I’ll help you.

its a great tutorial but you can put a few more pics of what the output actually looks like to make it a better tutorial, because it makes it easier to refer back to and see what codes actually correspond with what.

Hi, thanks for these tutorials. Thanks to them I’ve created my a nice theme. Anyway, is there a way to edit the_ID();? I want to use the ID as a parameter for a function…

I don’t know.

Fresh01:

Hey SP!

Great tutorial! Really helping me A LOT!

Anyway, I have one question: I have done everything up to here exactly like you have, but my blog shows only the most recent post title, and not all of them like your example…I have about ten posts. Any ideas?

Thank You.

Fresh01:

Nevermind!!

I found the setting under the writing options in admin.

whoaa.. this chapter is starting to challenge me and im getting errors… but it is because of “)” and “>” are interchange when I typed it. Nice tutorial :D

I just came across something else. When I add the code in the loop to display the post titles, save my index.php file, and refresh my web page is completely blank.

I have gone back three times to ensure the coding is exactly how you have it.

Any ideas?

Didi:

I believe i typed correct , but i can see any posts
============

Are you trying to post codes? Codes don’t show up in comments.

Just completed Chapter 5 of your series. Thats all for today… I am loving it. Thanks a lot for this series

eej sp!

Great tutorial! All works fine but now I have this small problem.

I saw Fresh01 dropping the same question above: I only see one title while I created three.

It shows one title so it seems there are no parser errors etc. Has this something to with my settings in wp-admin?

thanks!

yo sp!

Pretty strange but it works now! Nevermind my question, I go to the next lesson now.

herman

calskin:

Great tutorial. I had a couple wrinkles (just typos really) but you’re right, you just need to start over and it’ll work if you do it enough times.

CHAD:

Hi, I love your writing style and the examples you provide. This is byfar the best wordpress tutorial site I have ever seen. Thank you so much for providing this valuble resource, and especially for free. I look forward to more tutorials in the future!! And I would also be glad to donate to you if you had a donation link.

I have a problem. So far, I have followed everything with no problems except when trying to do “the loop”. I typed everything in correctly and have double checked. However when I go to display “hello world”, I get this error:

Fatal error: Call to undefined function the_posts() in C:\xampp\htdocs\…\index.php on line 31

I don’t have a function named “the_posts()”. I named mine just like yours, “the_post()”, without the s. What have I done wrong?

Thank you!
Chad!

check on line 31 to see if you’ve added an extra “s” somehwere

CHAD:

Thanks for the quick reply!

Well, “the_post()” is not even on line 31. It’s line 33 :) I checked everything and all looks good. I even copied and pasted all your code with still the same problem. Why does it still say call to undefined “the_posts()”, when I have it without the “s”. This is weird.

CHAD:

Okay, I fixed it. It was nothing in the code. I am not sure how this happened but somehow the “index.php” I was working on wasn’t updating when I hit save. I’ve never had that happen before but it’s all good now.

So, problem solved!! Thank You for the quick reply and help.
Chad

Rosewynde:

GREAT tutorial SP thank you! I’m pretty good at Basic HTML and CSS as I’ve written my own personal pages for years and have a background in programing. But I was struggling to understand the overload of php and div commands I was seeing in the code. Your explanations are helping a lot.

Rosewynde:

I also ran into the problem where after making additional blog posts and refreshing the browser, only the initial post showed up. I did end up finding the solution but thought others might want to know what I found.

I spent several minutes checking all the code, loading another theme and refreshing the theme test screen (which still showed only 1 post), verifying I had actually saved AND published the post, and even checked through all my wordpress settings. All to no avail.

Then I suddenly realized and had to laugh at myself. In testing things I had clicked on the link for the name of the post. That meant i was on the page for that single post and not the one that showed all the recent posts. So of course it showed only that single post ; D

Anyways, theres a really easy way to check. If your browser bar reads out as http://localhost/wordpress/?p=* (where star is the assigned posts number), then your on a single post page ; D Click on the title for the blog which you should have made into a link to the main post page (http://localhost/wordpress/). All your posts should show up :)

wow.. im in lesson 5.. im really enjoying this.. :)

Addies:

What are these “:” (colons) between the code?

Please see here

Addies:

I added the line, but it isn’t showing in the last comment entry.

Could you please help me Tung with what I asked above?

Here is the line, let’s see if it shows here …

Moreover, why there is a semi-colon after the_post(); (to end it) but there is colon after have_posts. I have an idea but I need to confirm whatever I am understanding is correct. Please help with this. Thank you Tung.

You are doing a great job! :)

Post your question at the support forums and I’ll take a look at it.

hugo:

hey
I went through the tutorial this far. When I click on the titles of the blogs…like hello world for example, I get an error message that says “access forbidden. you do not have access…blah blah…contact the webmaster..LOL…”
so yeah

i’m pretty sure LOL wasn’t apart of the error message :) . bring this to your forum and show me your blog or a screenshot of it and i’ll try to look into it.

This is the best tutorial I’ve seen sofare. I’ve been wanting to creat my own them for my blog, and this tutorial is exectly what I needed.

Thank you.

Ron Rinaldi:

I think your information here is great. I am planning to use this tutorial. However, can you PLEASE change the colors on your site? Your dark scheme may seem catchy, but it is very difficult to read.

Thank you.

jicoro:

Everything goes smoothly for me…thanks, I used wamp instead of xamp, it’s easier and it works the same ,,,@o@

Great Tutorial. Easy to follow and a real page turner!
I hope I can find something this good for creating a Joomla Theme …

Ken:

Thanks for the great tutorial. It’s all starting to make sense now. Here’s a little tip. I kept getting an error on line 31 and I compared it to yours over and over and I couldn’t see it. So I just copied your line and pasted it right below mine and then the error became obvious. Frustration over!

James Bates:

Hello. I’m trying your course and am up to here and have copied the code exactly however it is only bringing up my first blog post not the additional ones? Where could the problem be?

Cheers..

J

[...] Template Files and Templates #3 Starting Index.php #4 Header Template #4b Header Template Continues #5 The Loop #5b The Content #5c Postmetadata #5d Else, Post ID, Link Title #5e Posts Nav Link #6 Sidebar (and [...]

I found that using ‘ instead of ” helped solve a lot of problems in the code….

Hey, great tutorial thus far, but can’t make my posts show up!!

have uploaded here http://mildfuzz.com/index.txt

Cheers for the work, most appreciated!!

Rob:

Hey, thanks for the awesome tutorial. Got a little snag though on my end. Got XAMPP installed finally, then I finally figured out how to create a db in my local server, but now when I try to do a test post with an image I get an error

“cannot write to disc” when I try to import a test image. How do I correct that? I’ve tried creating the wp-theme/upload directory but that didn’t do it.

Any suggestions?

(sorry, this was posted on the wrong page of the tutorial)

sorry, that link didn’t seem to do anything

this should work

http://mildfuzz.com/text_upload/download.html

my email address is at the bottom of the text file, feel free to contact me that way if you can see where I am going wrong, but will check here for a response also

many thanks

Please ignore, I have fixed the problem!!! Thanks again for a great tutorial!!

Seth:

Man, thanks so much! You make this too easy, really. Of course, this is just the beginner stuff, but I can’t explain to you how exciting it is to see this stuff work for me! I’ve bought so many books on PHP and whathaveyou, and man, if you’d written any of them I think I’d have a firm enough grasp on key concepts to… Well, let’s just say you’re a good teacher. Thanks so much :D

zimzallabim:

Hi SP thanks for the tut – its great. I’m having the same problem as Hugo was having earlier on, “Access forbidden – contact webmsater” and all that jazz – I went to have a look on the support forums however I wasn’t in need of tramidol or any ‘delivered to your door medicines’ that some one had spammed the forum with. I was wondering whether you had solved the problem that Hugo was having and if so, do you remember what it was and how you solved it?

Many thanks,

Zim :D

zimzallabim:

Hi again managed to work it out by myself – for anyone with the same problem that I had – its more than likely that part of the code was wrong – if in doubt copy the code out exactly as above and I’m sure that it will work.

Zim

Sam:

Hi SP, great tutorials, really enjoying them!

Just having one problem: I have created several posts but the newest one won’t display as a hyperlink but the rest do, any ideas?

Thanks

Your very first illustration (circled in red) shows:

<a href=”‘>

The part . . . . ?>’> should be ?>”> (Sorry if this error was already commented on)

I’m old(er) your keeping my mind alert, thank you for this learning experience!!

[...] Now, every template contains something called “The Loop” http://codex.wordpress.org/The_Loop. Basically, if WP were a cake, the loop can be seen as the spongy base, and all the extra styling should be added around the loop like frosting. Here is a very nice explanation of The Loop. [...]

this is a very good tutorial.

i will make my own theme for myself.

thank you sir

[...] Template Files and Templates #3 Starting Index.php #4 Header Template #4b Header Template Continues #5 The Loop #5b The Content #5c Postmetadata #5d Else, Post ID, Link Title #5e Posts Nav Link #6 Sidebar (and [...]

ryan:

Hey I got a similar issue –

I went through the tutorial this far. When I click on the titles of the blogs…like hello world for example, I get an error message that says “access forbidden. you do not have access

Is this supposed to happen at this point in the tutorial?

ryan:

Just figured it out. the access forbidden error is caused by the ” ” marks within the I had them backwards.