You may have noticed that I recently added a list of “Recent Headlines” to some of the pages that describe my Projects on this site. This is handled dynamically through WordPress, so that if I ever post a new blog entry relating to one of those projects, it automatically appears on the appropriate project page.
By default, Pages within WordPress will look for a file called “page.php” within your theme, and use that to control their layout/visual appearance. If that file isn’t there, then they’ll use “index.php” (read more about the WordPress Theme Hierarchy). You also have the option of creating custom Page Templates, and then selecting a specific one to use when you create a Page. That’s what I did, using something like the following process:
- Go into your theme directory and make a copy of your “page.php” file. I called mine “page-headlines.php”
- Open up page-headlines.php in your favorite text editor, and paste the following code after you output the content (and possibly any footer/meta information) for the Page. This is going to be different for each theme, but generally they will use <?php the_content(); ?> somewhere (which outputs the content of the Page). Make sure you don’t mess up any DIVs or other tags that are required for layout. Here’s the code you need:
<?php if ( $tag = get_post_custom_values( 'headlines-tag' ) ) : ?> <?php $headlines = get_posts(array('tag'=>$tag)) ?> <?php if ( count( $headlines ) ) : ?> <h2>Recent Headlines</h2> <ul> <?php foreach ( $headlines as $post ) : setup_postdata( $post ); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ul> <?php endif; ?> <?php endif; ?>
- At the top of that file, you need to make sure you have a unique name for selecting this template. The name can be pretty much anything, but must be included as shown below:
<?php /* Template Name: Project Details with Headlines */ ?>
- Upload that file into your theme directory.
- Go to Pages > Add New (or edit an existing one) in wp-admin, and add a title/Page content if you need to.
- On the right of the Page Edit screen (unless you moved it), there will be a block titled “Attributes” which includes a “Template” option. Select your option from the list.
- Here comes the magic bit. Jump over to the “Custom Fields” block, and add a custom field with the name set to “headlines-tag” (which you’ll notice is what we’re querying in the code above). Set the value to any tag name that you’ll then use on a blog post (or may already have used).
- Publish the page and then go and view it. If you have any posts in your blog that match the “headlines-tag” you specified, they should show up in a list underneath your Page content.
You can customize the output however you like, using the same sort of template tags as you have available in The Loop. Get creative. Oh, and there’s another way to do this, using shortcodes, described over at SmashingMagazine.