I suppose it’s fitting that my first article for the Register concerns WordPress on which this site is built. I wanted to adapt WordPress’s blog format to a more static feel. Most pages are static – they are not blogs. However, I wanted to have blog-like articles on some pages. Different pages might show different types of articles, so I needed a way to display only certain categories of articles on each page.
I developed the solution mainly from the help found in the WordPress Codex (link). I combined the suggested technique with some code from my template. The static content of each page is the only entry in the posts for the page so this is displayed first. Then a new query is issued searching for posts with a specific category. These categories are defined in the custom fields of the page (set using the WordPress dashboard). CSS is used so that the static content is rendered differently than the posts (articles). I put all of this in a new page template and use this whenever I make a new page. If no categories are defined in the page’s custom fields, then it looks like a normal static page. Here is the template as of today:
<?php /* Template Name: Eds Page Template */ ?> <?php get_header(); ?> <div id="content"> <!-- this first block will display the page content --> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div id="post-<?php the_ID(); ?>"> <h2><?php the_title(); ?></h2> <div> <?php the_content('<p>Read the rest of this page »</p>'); ?> <?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?> </div> </div> <?php endwhile; endif; ?> <!-- this next block will display all of the posts in the requested categories --> <?php // which posts are displayed depends on the categories associated with the page if (is_page() ) { $categories = get_post_meta($posts[0]->ID, 'post_categories', true); } if ($categories != null && $categories != ''){ $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( // Change these category SLUGS to suit your use. 'category_name' => $categories, 'paged' => $paged ); $list_of_posts = new WP_Query( $args ); while ($list_of_posts->have_posts()){ $list_of_posts->the_post(); // Display content of posts //get_template_part('content', get_post_format()); ?> <div id="post-<?php the_ID(); ?>"> <div><?php the_time('F jS, Y') ?></div> <!-- made each post title a link to the article's page --> <a href="?p=<?php get_permalink( the_ID() ); ?>"> <h2><?php the_title(); ?></h2> </a> <div> <?php the_excerpt('<p>Read the rest of this page »</p>'); ?> <?php wp_link_pages(array('before' => '<p><strong>Pages:</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?> </div> </div> <?php } } ?> <?php edit_post_link('Edit this entry.', '<p>', '</p>'); ?> </div> <?php get_sidebar(); ?> <?php get_footer(); ?>