Tema Para WordPress Parte 4: Criando os Subtemplates

Aos leitores do feed:

Como esse post ficou muito longo, está dividido em 3 partes, para acessar, o jeito é vir até o blog, já que posts paginados aparecem pela metade.

Antes de continuar, você deve estar lembrado que havia um erro de XHTL no código para corrigir.

Se você não encontrou, aqui vai a dica. No footer.php, antes da tag </body>, acrescente </div>.

Nem sempre uma tag faltando vai quebrar o template de um blog, mas vai, sim, fazer com que o código deixe de validar.

Corrigida a lição de casa, vamos à aula de hoje. Prepare um café porque hoje a coisa vai longe :-D .

Antes de estilizar o CSS do nosso tema, vamos criar os subtemplates, que personalizam a exibição das páginas fixas, arquivos, categorias etc.

Páginas Fixas

O subtemplate page.php é responsável pela exibição das páginas fixas, como páginas de contato, sobre, política de privacidade e outras. São páginas que não entram na cronologia de publicação do blog, daí o termo “fixas”.

Por sua característica informativa, normalmente dispensam comentários e não são categorizadas. Por isso, são um pouco diferentes do template index.php.

Vá até o seu index.php, copie todo o código e cole no bloco de notas ou no editor de texto de sua preferência.

Localize o trecho abaixo:

<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

Substitua por esse:

<h1><?php the_title(); ?></h1>

Localize os códigos abaixo e delete todos eles:

<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?>

--></small>
<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>  <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></p>
<div class="navigation">
<div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
</div>

Salve como page.php, junto dos outros templates do seu tema.

Arquivos

Copie o código do seu index.php, cole no editor de textos e insira o código abaixo logo após <?php if (have_posts()) : ?>.

<?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
<?php /* If this is a category archive */ if (is_category()) { ?>
<h2 class="pagetitle">Archive for the &#8216;<?php single_cat_title(); ?>&#8217; Category</h2>
<?php /* If this is a tag archive */ } elseif( is_tag() ) { ?>
<h2 class="pagetitle">Posts Tagged &#8216;<?php single_tag_title(); ?>&#8217;</h2>
<?php /* If this is a daily archive */ } elseif (is_day()) { ?>
<h2 class="pagetitle">Archive for <?php the_time('F jS, Y'); ?></h2>
<?php /* If this is a monthly archive */ } elseif (is_month()) { ?>
<h2 class="pagetitle">Archive for <?php the_time('F, Y'); ?></h2>
<?php /* If this is a yearly archive */ } elseif (is_year()) { ?>
<h2 class="pagetitle">Archive for <?php the_time('Y'); ?></h2>
<?php /* If this is an author archive */ } elseif (is_author()) { ?>
<h2 class="pagetitle">Author Archive</h2>
<?php /* If this is a paged archive */ } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?>
<h2 class="pagetitle">Blog Archives</h2>
<?php } ?>

Para evitar a geração de conteúdo duplicado, o que não vai ajudá-lo em nada na indexação junto aos mecanismos de busca em geral e Google em particular, vamos substituir o código responsável pela exibição dos posts.

Localize <?php the_content('Read the rest of this entry &raquo;'); ?> e substitua por <?php the_excerpt() ?>.

Salve como archive.php.

Comentários

Os comentários que serão exibidos junto aos posts são gerados pelo arquivo comments.php. para criá-lo, copie o código abaixo, cole no editor de textos e salve-o como comments.php.

O código é uma versão ligeiramente modificada do encontrado no tema padrão do WordPress. Ele exibe os comentários separados dos trackbacks, que vem abaixo dos comentários normais.

<?php // Do not delete these lines

if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']))

die ('Please do not load this page directly. Thanks!');

if (!empty($post->post_password)) { // if there's a password

if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password) {  // and it doesn't match the cookie

?>

<p class="nocomments">This post is password protected. Enter the password to view comments.</p>

<?php

return;

}

}

/* This variable is for alternating comment background */

$oddcomment = 'class="alt" ';

?>

<!-- You can start editing here. -->

<?php if ($comments) : ?>

<h3 class="comments"><?php comments_number('No Responses', 'One Response', '% Responses' );?> to &#8220;<?php the_title(); ?>&#8221;</h3>

<ol class="commentlist">

<?php foreach ($comments as $comment) : ?>

<?php $comment_type = get_comment_type(); ?>

<?php if($comment_type == 'comment') { ?>

<li <?php echo $oddcomment; ?>id="comment-<?php comment_ID() ?>">

<?php echo get_avatar( $comment, 32 ); ?>

<cite><?php comment_author_link() ?></cite> Says:

<?php if ($comment->comment_approved == '0') : ?>

<em>Your comment is awaiting moderation.</em>

<?php endif; ?>

<br />

<small class="commentmetadata"><a href="#comment-<?php comment_ID() ?>" title=""><?php comment_date('F jS, Y') ?> at <?php comment_time() ?></a> <?php edit_comment_link('edit','&nbsp;&nbsp;',''); ?></small>

<?php comment_text() ?>

</li>

<?php

/* Changes every other comment to a different class */

$oddcomment = ( empty( $oddcomment ) ) ? 'class="alt" ' : '';

?>

<?php } /* End of is_comment statement */ ?>

<?php endforeach; /* end for each comment */ ?>

</ol>

<h3 class="comments">Trackbacks</h3>

<ol class="commentlist">

<?php foreach ($comments as $comment) : ?>

<?php $comment_type = get_comment_type(); ?>

<?php if($comment_type != 'comment') { ?>

<li><?php comment_author_link() ?></li>

<?php } ?>

<?php endforeach; ?>

</ol>

<br/><br/>

<?php else : // this is displayed if there are no comments so far ?>

<?php if ('open' == $post->comment_status) : ?>

<!-- If comments are open, but there are no comments. -->

<?php else : // comments are closed ?>

<!-- If comments are closed. -->

<p class="nocomments">Comments are closed.</p>

<?php endif; ?>

<?php endif; ?>

<?php if ('open' == $post->comment_status) : ?>

<h3 class="comments">Leave a Reply</h3>

<?php if ( get_option('comment_registration') && !$user_ID ) : ?>

<p>You must be <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?redirect_to=<?php echo urlencode(get_permalink()); ?>">logged in</a> to post a comment.</p>

<?php else : ?>

<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">

<?php if ( $user_ID ) : ?>

<p>Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Log out &raquo;</a></p>

<?php else : ?>

<p><input type="text" name="author" id="author" value="<?php echo $comment_author; ?>" size="22" tabindex="1" />

<label for="author"><small>Name <?php if ($req) echo "(required)"; ?></small></label></p>

<p><input type="text" name="email" id="email" value="<?php echo $comment_author_email; ?>" size="22" tabindex="2" />

<label for="email"><small>Mail (will not be published) <?php if ($req) echo "(required)"; ?></small></label></p>

<p><input type="text" name="url" id="url" value="<?php echo $comment_author_url; ?>" size="22" tabindex="3" />

<label for="url"><small>Website</small></label></p>

<?php endif; ?>

<!--<p><small><strong>XHTML:</strong> You can use these tags: <code><?php echo allowed_tags(); ?></code></small></p>-->

<p><textarea name="comment" id="comment" cols="90%" rows="10" tabindex="4"></textarea></p>

<p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />

<input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" />

</p>

<?php do_action('comment_form', $post->ID); ?>

</form>

<?php endif; // If registration required and not logged in ?>

<?php endif; // if you delete this the sky will fall on your head ?>

Salve como comments.php, junto com os outros arquivos do tema.

Post Individual

É o que vai gerar a visualização dos posts, com os comentários e links para os posts próximo e anterior.

Copie seu index.php e cole no editor de textos, como você já fez tantas vezes.

Localize o código abaixo:

<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent

Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

E substitua por esse:

<h1><?php the_title(); ?></h1>

Localize e delete o código abaixo:

<div class="navigation">
<div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
</div>

Acrescente o seguinte código, logo após <?php endwhile; ?>.

<?php comments_template(); ?>

<br clear="all"/>

<div class="navigation">

<div class="alignleft"><?php previous_post_link('&laquo; %link') ?></div>

<div class="alignright"><?php next_post_link('%link &raquo;') ?></div>

</div>

Página de Erro

É a famigerada página de erro 404, exibida quando um link que não existe mais é acessado.

Copie o index.php, cole no editor de textos e substitua toda a área responsável pela geração do conteúdo, desde <?php if (have_posts()) : ?> até <?php endif; ?> pelo código abaixo.

<h2 class="posttitle">Not Found</h2>
<?php include (TEMPLATEPATH . "/searchform.php"); ?>

Formulário de Busca

Essa é fácil, e acho que o título é auto-explicativo. Copie o código abaixo, cole no editor de textos e salve como searchform.php.

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div><input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
</div>
</form>

Se você quiser uma página com resultados de busca personalizada, copie seu index.php, cole no editor de textos e acrescente <h2>Search Results</h2> logo abaixo de <?php if (have_posts()) : ?>, substitua <?php the_content('Read the rest of this entry &raquo;'); ?> por <?php the_excerpt() ?> e salve como search.php.

Funções

Copie o código abaixo e salve como functions.php. Experimente suas widgets, que devem funcionar a partir de agora.

<?php
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name'=>'LeftSidebar',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2>',
'after_title' => '</h2>',
));

register_sidebar(array(
'name'=>'RightSidebar',
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2>',
'after_title' => '</h2>',
));
?>

Hoje temos um brinde para os assinantes do feed, os principais arquivos que você utilizou até agora, traduzidos para o português. Quem já é assinante vai ver um link para download no final do texto.

Se por acaso esqueci de algo, avise nos comentários.

Não é assinante ainda? Clique aqui e resolva seus problemas.

Escrito por

j. noronha criou esse site em 2006, além de outros menos memoráveis.

Siga-me no Twitter

Gostou? Receba mais no seu email, é grátis!