Quite often recently when building WordPress themes for smaller sites (ones that have a brochure feel, but have a blog section), the design has included an area on the frontpage, or footer that shows a list of the latest blog posts.
I’ve got a little loop that I use for this area, shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
< ?php global $post; $tmp_post = $post; $myposts = get_posts('numberposts=3'); foreach($myposts as $post) : setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"> <span class="date">< ?php the_date('d F Y');?></span><br /> <span class="title">< ?php the_title(); ?></span><br /> <span class="description">< ?php echo htmlentities(cut_str_length(strip_tags(get_the_content()), 80)); ?></span> </a></li>< ?php endforeach; $post = $tmp_post; ?>
Apart from the cut_str_length function – which I haven’t included – this makes use of WordPress functions and in-built PHP functions to strip the text out of the content so that I have don’t have any images in the way or any formatting, so I can apply my own.
Since the setup_postdata() function seems to have a “special relationship” with $post, we grab a copy before and restore after the function so that you can use it anywhere in the page – inside, or outside the loop – and it shouldn’t affect the rest of your page.