21Apr
0 Comments
How to Display Posts on Pages | Wordpress Wednesday #3
This post contains just one very quick and simple reason, along with the code for using Posts on Pages. If you are looking for detailed information about Wordpress loops, check out the Codex.
Example of use:
You have built a personal portfolio website, powered by Wordpress. You want to display all of your portfolio items on a Page named ‘portfolio’. Ideally, the items would be generated using Posts.
By combining posts and pages, you can supply static content for the Page and have dynamic content which changes using Posts.
What we’re going to do…
Our goal is to display 15 most recent Posts from the category ‘portfolio’. We will order each item by date.
So what is the loop? (from the Codex):
The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post.
The code
Let’s get straight to it, I will leave it on one clode block but I have seperated different sections with an empty line.
<?php query_posts ('orderby=date&category_name=portfolio&posts_per_page=15'); ?>
<?php if (have_posts()): while (have_posts()): the_post(); ?>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt();?>
<a class="more" rel="group" title="<?php the_title(); ?>" href="<?php the_permalink() ?>">More »</a>
<?php endwhile; else: wp_reset_query(); ?>
<?php endif; ?>
The code is pretty straightforward, but here is a more detailed break down.
- Look for some posts please, but I only want them from the category ‘portfolio’, I only want 15 of them and when you find them, order them by date.
- Start the Wordpress Loop BUT only if you found the posts I was asking for. (read more about the loop in the Codex.
- Anything contained within the Wordpress loop will be output for each post the query finds. Here we will display the title, an excerpt and a ‘read more’ button for each post we find.
- Finishing up we end the ‘while’ loop, end the ‘if’ statement and we use ‘wp_reset_query’ to make sure this query will not interfere with any other queries which are executed later on.
Is that it?
The query posts function probably has limitless use. It is up to you to think of dynamic ways of adding content using this method. Suggestions might include recent posts, popular posts, posts from a category ‘personal’ to display on your ‘about’ page.
Can you think of any more?
This post has no comments.
Leave your reply