We’re going to be working in the Loop again, but this time between the endwhile function and endif function. Anything that we put here will only appear if there are posts to display (which is why they are before the endif function). Therefore, in this part we’ll be working in the space marked with an ellipsis below.
<?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> code for posts and such, done in part 4 <?php endwhile; ?> . . . <?php endif; ?>
One important thing to include are “back” and “forward” links – links that will allow users to navigate back and forth through your posts. Newest posts will be on the homepage and older posts on further pages. The codes for older and newer entries are below.
<?php next_posts_link('← Older Entries') ?> <?php previous_posts_link('Newer Entries →') ?>
You can again edit the text in italics to what you want the links to look like. Wrap them in a div, use a
h3 for them if you so wish – it’s up to you. Get a little creative!
Now we should include a notification that users will stumble upon if they try to visit a page on your website that doesn’t exist, but this code will take care of that. Put this code after those back/forward links, and users will be notified that the page they are looking for doesn’t exist.
<?php else : ?> <h1>Not found</h1> <p> Sorry, but the page you requested does not exist.</p> <?php get_search_form(); ?>
Basically, by including this, the Loop is telling WordPress “if posts exist, display them like this; if not, display this”. The <?php else : ?> statement takes care of that.
If you want to customise the search results you will need to view a separate tutorial.
You can now save index.php and upload it to your theme folder,
Alternatively, you can create a 404.php page. This is just extra and is not mandatory for your theme. It simply consists of the index file without the Loop.
<?php get_header(); ?> <h3>Error 404 - Not Found</h3> <?php get_footer(); ?>
Stay tuned, in the next section we’ll be looking at the page and single templates.