WordPress: ficheros de template para categorias

[Fuente: http://codex.wordpress.org/Category_Templates]

Introducción

Desde que llegaron los Themes en WordPress 1.5,  cambiar el look and feel de tu web WordPress se ha hecho muy versatil. Por ejemplo, cuando un visitante de tu web hace click en un link de una de las categorias de tu site, es llevado a una page que lista los Posts de esa categoria en particular en orden cronológico empezando por el último. Hay muchas posibilidades de visualizacion, desde incluir el post completo a solo resumenees, y que información adicional (titulo, autor, fecha de publicacion, hora de la ultima modificacion, etc). Cada Theme tiene elecciones diferentes y tu querrias saber cambiarlas.

En este articulo se explica como cambiar lo que sucede cuando el visitante de tu blog esta visitando las páginas de categoria de tu web.Esto inclute hacerlo utilizando los ficheros de template.

Qué fichero de Template utilizamos?

El primer paso para modificar lo que sucede cuando alguien visita la pagina de una categoria es averiguar cual de los ficheros del theme va a ser utilizado para mostrar los posts. Esto viene en Template Hierarchy.

En el caso de las categorias, la jerarquia es muy simple. Por ejemplo, supongamos que el ‘slug’ de la categoria es ‘news’ y el Id de la categoria es 6. Entonces el Template Hierarchy especifica que WordPress utilizará el primer fichero de template que encuentre en la carpeta del theme de los siguientes:

  1. category-slug.php (Note: available with Version 2.9)
  2. category-ID.php
  3. category.php
  4. archive.php
  5. index.php

Asi , siguiendo con el ejemplo , si no existe category-news.php , WordPress mirará que haya un category-6.php y asi.

Con category.php cambias el look de todas las categorias.

Con archive.php cambiamos el look de todas las páginas archivadas.

Cambiando el index.php cambias el look de todo el blog.

Si necesitas crear un nuevo fichero, es una buena idea empezar haciendo una copia del siguiente fichero en la jerarquia. Por ejemplo, si queremos un look especial para la categoria 6 , empezamos por hacer una copia del fichero category.php, si este no esta, del archive.php y asi.

Ejemplos

En estos ejemplos , cuando decimos ‘edita el fichero de template’ nos referimos a editar el fichero que se ha elegido en el apartado anterior.

Añadiendo texto a la Category Pages

Texto estático sobre los Posts

Supongamos que queremos mostrar texto estático antes de la lista de posts en la category page. Por estático queremos decir que el texto permanece el mismo, no importa que posts sean mostrados debajo, y es para todas las categorias. Para hacerlo:

Encima de la seccion Loop (The Loop) del fichero de template en el que estes, inserta el siguiente código (no tiene misterio):

<p>This is some text that will display at the top of the Category page.</p>

Texto distinto en algunas paginas de categoria

A slightly more complex possibility is that you want different text to display depending on which category page the visitor is viewing. Then you would add the “default” text to the main category.php file, and create special category-#.php files (with their own version of the text, as described in the Introduction) for each category that needs special text at the top.

This does however create a lot of files in your theme directory, and can be avoided using the following code OUTSIDE the loop:

<?php if (is_category('Category A')) : ?>
<p>This is the text to describe category A</p>
<?php elseif (is_category('Category B')) : ?>
<p>This is the text to describe category B</p>
<?php else : ?>
<p>This is some generic text to describe all other category pages,
I could be left blank</p>
<?php endif; ?>

This does the following. Checks to see if we are looking at Category A, if we are then show the first bit of text, but if we’re not then check if we are looking at Category B. If we are then show that bit of text, and finally, if it is neither Category A or B, then show this default text.

Text Displaying Only on First Page of Archive

Another thing that can happen is that if your Category contains more posts than will fit on one page (according to the Options for Blog Reading you have set in the Administration panels of your blog), the category archive will split into multiple pages. And maybe you only want to display your static text if the viewer is on the first page of results, or you want to display different text for the other pages.

To make this happen, you can use a PHP if statement, which looks at the value of the $paged WordPress variable ($pagedis equal to the page number: 1 for the first page of results, 2 for the second page, etc.). It may sound complicated, but it’s actually not too bad. Just put the following above The Loop:

<?php if ( $paged < 2 ) : ?>
<p>Text for first page of Category archive.</p>
<?php else : ?>
<p>Text for subsequent pages of Category.
Can be left out.</p>
<?php endif; ?>

Category Name

Another possibility is to put the category name at the top of the page. If this is not already part of your template, you can add it by doing something like this, above The Loop:

<p>Category: <?php single_cat_title(); ?></p>

Modificando como los Post son mostrados

Excerpts vs. Full Posts

Perhaps you are looking to cut down on the size of your Category pages. You could do this by displaying excerpts rather than the entire content of each Post. To do this, you will just need to find where it says the_content() inside The Loop in your Template, and replace it with the_excerpt(). These will most likely be inside PHP tags:

  <?php the_excerpt(); ?>
and
  <?php the_content(); ?>

Conversely, if your Theme is currently displaying excerpts and you want full posts, replace the_excerpt with the_content.

Display Images Linking to Full Posts

Another thing that is interesting to do in a category archive page is to replace the post content with an image that links to your post. To do this, you will first need to put images into the Excerpt sections of your posts. Here’s how to do that, for one post:

  1. Upload an image on the post editing screen.
  2. Switch to the “Code” editor, rather than the “Visual” editor.
  3. Use the Uploads / Browse tab to insert the image into your post. Make sure to insert the full-sized image, with no link.
  4. Copy the inserted HTML img tag, and paste it into the “Optional Excerpt” section of the post editing screen.
  5. Finish writing the post content (you can remove the image), and publish the post.

Now you will need to modify your template. We’ll use a trick: the the_excerpt_rss() Template Tag does not put a paragraph tag around the excerpt. So we can use it to insert the img HTML and put it inside a link. Here’s what you need to put into your Template, in place of using the_content:

<a href="<?php the_permalink() ?>">
<?php the_excerpt_rss(); ?>
</a>

Caveat: using the excerpt this way may affect your RSS feed, because it places an img tag in the excerpt, instead of text. So if you are going to do this, you probably want to set your options so that the full posts are put in RSS feeds, rather than excerpts.

What categories do you show to the visitors?

You can limit the categories in archive and other pages with this code:

<?php query_posts('cat=1&posts_per_page='.get_option('posts_per_page')); ?>

This is placed before the Loop.

query_posts documentation: http://codex.wordpress.org/Template_Tags/query_posts

The get_option('posts_per_page') part of the code uses your blog’s options to show a limited number of posts.

This code is very useful if you would like to separate the categories. With this code you can make multiple archives. For example:

<?php if (have_posts()) : ?>
 <?php if (is_month()) {query_posts('year='.get_the_time('Y').'&monthnum='.get_the_time('m').'&author_name=admin&cat=1&posts_per_page='.get_option('posts_per_page')); ?>
  <!-- Do stuff... ->
 <?php } ?>
 <?php while (have_posts()) : the_post(); ?>
  <!-- post's contents -->
 <?php endwhile; ?>
<?php endif; ?>

If you use this code in archive.php and navigate to http://yourblog.com/2008/02/, it will show you the admin user’s post that is posted on 2008.02. in the “first” category.

Further Reading