I’m using the following page template to display the posts in a single category and plan to format the first post differently than the others. This works as desired but I have the category_name hard coded in the template. I want to use this template for several different categories and would like to learn how to pass the category_name to the template from a link.
For example, the link to the desired page using the special template is http://wildcatweb.net/5th/ and ‘5th’ is also the category_name. How do I tell the template to get the category_name from the URL and use it in the template?
<?php
/*
Template Name: pageAssignments
*/ ?>
<?php get_header(); ?>
<div class="small-12 large-8 columns" id="content" role="main">
<header>
<h1 class="entry-title"><?php the_title(); ?></h1>
</header>
<!-- show latest post FULL -->
<?php query_posts('showposts=1&category_name=5th'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="lastest-post">
<h2 class="pagetitle"><?php the_title(); ?></h2>
<?php the_content(); ?>
</div><!--close .latest-post -->
<?php endwhile; endif; ?><!-- end lastest post -->
<!-- show older post excerpts -->
<?php query_posts('showposts=5&offset=1&category_name=5th'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="older-post">
<h3 class="pagetitle"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
<?php the_excerpt(); ?>
</div><!--.older-post -->
<?php endwhile; endif; ?><!-- end past-entry -->
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Rather than creating pages and assigning a template, I would use the
category_template
filter to load a specific template for all those particular categories. In this example I use a hardcoded array, but this could be adapted to load an option which stores the category slugs you want the template applied to.You then no longer have to query for these posts in the template, as the posts are already in the main query. (also, as an aside, never use
query_posts
).Within the template you can use
single_cat_title
to output the name.You also don’t have to use two queries and loops to style the first post differently, just check the
current_post
var in the loop to know what post you’re currently outputting.If you wish to use this template for multiple categories, presumably you have named it
category.php
?To get the name of the Term that is currently being displayed, use this (before you enter The Loop) –
And then replace –
With –
WordPress will use the first Template file it finds in your current Theme’s directory from the following list:
Source http://codex.wordpress.org/Category_Templates
You can add the category name by adding this code to the template before The Loop: