Archive for category The Basics

Simple Way to Make WordPress Comments Functionality Work on Your Theme / Blog / Website

Today I’ll show a very simple way to make comments function work on your WordPress website, if you are working with your own theme or modifying one that already exists. There are only three steps.
Hoje vou mostrar um jeito muito simples de fazer a função de comentários funcionar no seu site WordPress, se você está trabalhando com seu próprio tema, ou modificando um que já exista. São apenas três passos.

Step 1:

On your category page(e.g. category.php), put the code bellow, where you want the link for commenting to be shown(note that it is inside the loop). This link will take the user to your single.php page, where the comments will be displayed bellow the post.
Na sua página de categoria(por exemplo category.php), ponha o código abaixo, onde deseja mostrar o link para comentar(note que ele está dentro do loop). Este link levará o usuário à sua página single.php, onde os comentários serão exibidos abaixo do post.

<?
 query_posts("category_name=yourcategory");
// here we start the loop
if (have_posts()) :		 	 
  while (have_posts()) : the_post();	
?>
   // this line displays the link for commenting, going to the single.php file when clicked
   <a href="<?php comments_link(); ?>">
       <?php comments_popup_link('Text you want to display','Text for one comment','% Text for various comments', 'Text for more'); ?>
   </a>
<?
  endwhile;
endif;
?>

Step 2:

Now,let’s put the code bellow on single.php file.
Agora, vamos colocar o código abaixo no arquivo single.php

<?
// here we start the loop
if (have_posts()) :		 	 
  while (have_posts()) : the_post();	
?>
   <a href="<?php comments_link(); ?>">
      <?php comments_popup_link('Text you want to display','Text for one comment','% Text for various comments', 'Text for more'); ?>
      </a>
<?
  // this line displays the comment form and the comment list
  comments_template();
  endwhile;
endif;
?>

Step 3:

Save the code bellow as comments.php, on your theme directory. CSS classes and styles can be changed if wanted.
Salve o código abaixo como comments.php no diretório de seu tema. Classes CSS e estilos podem ser mudados se desejado.

<?php
	if ( 'comments.php' == basename($_SERVER['SCRIPT_FILENAME']) )
		die ( 'Please do not load this page directly. Thanks!' );
?>
<link href="style.css" rel="<? bloginfo('stylesheet_url'); ?>" type="text/css" />

			<div id="comments">
<?php
	$req = get_option('require_name_email'); // Checks if fields are required. Thanks, Adam. ;-)
	if ( !empty($post->post_password) ) :
		if ( $_COOKIE['wp-postpass_' . COOKIEHASH] != $post->post_password ) :
?>
				<div class="nopassword"><?php _e('This post is protected. Enter the password to view any comments.') ?></div>
			</div><!-- .comments -->
<?php
		return;
	endif;
endif;
?>
<?php if ( $comments ) : ?>
<?php global $sandbox_comment_alt ?>

<?php /* numbers of pings and comments */
$ping_count = $comment_count = 0;
foreach ( $comments as $comment )
	get_comment_type() == "comment" ? ++$comment_count : ++$ping_count;
?>
<?php if ( $comment_count ) : ?>
<?php $sandbox_comment_alt = 0 ?>

				<div id="comments-list" class="comments">
					<h3><?php printf($comment_count > 1 ? __('<span>%d</span> Comentários') : __('<span>Um</span> Comentário'), $comment_count) ?></h3>

					<ol>
<?php foreach ($comments as $comment) : ?>
<?php if ( get_comment_type() == "comment" ) : ?>
						<li id="comment-<?php comment_ID() ?>">
							<div class="datahora">Por <a href="<?php comment_author_url(); ?>"><?php comment_author(); ?></a> em <?php printf(__('%1$s às %2$s'),
										get_comment_date(),
										get_comment_time(),
										'#comment-' . get_comment_ID() );
										edit_comment_link(__('Edit'), ' <span class="meta-sep">|</span> <span class="edit-link">', '</span>'); ?></div>
<?php if ($comment->comment_approved == '0') _e("\t\t\t\t\t<span class='unapproved'>Seu comentário está esperando moderação.</span>\n") ?>
							<span class="comentario"><?php comment_text() ?></span>
						</li>
<?php endif; /* if ( get_comment_type() == "comment" ) */ ?>
<?php endforeach; ?>

					</ol>
				</div><!-- #comments-list .comments -->

<?php endif; /* if ( $comment_count ) */ ?>
<?php if ( $ping_count ) : ?>
<?php $sandbox_comment_alt = 0 ?>

				<div id="trackbacks-list" class="comments">
					<h3><?php printf($ping_count > 1 ? __('<span>%d</span> Trackbacks') : __('<span>Um</span> Trackback'), $ping_count) ?></h3>

					<ol>
<?php foreach ( $comments as $comment ) : ?>
<?php if ( get_comment_type() != "comment" ) : ?>

						<li id="comment-<?php comment_ID() ?>" class="datahora">
							<div class="datahora"><?php printf(__('Por %1$s em %2$s às %3$s'),
									get_comment_author_link(),
									get_comment_date(),
									get_comment_time() );
									edit_comment_link(__('Edit' ), ' <span class="meta-sep">|</span> <span class="edit-link">', '</span>'); ?></div>
<?php if ($comment->comment_approved == '0') _e('\t\t\t\t\t<span class="unapproved">Your trackback is awaiting moderation.</span>\n') ?>
							<?php comment_text() ?>
						</li>
<?php endif /* if ( get_comment_type() != "comment" ) */ ?>
<?php endforeach; ?>

					</ol>
				</div><!-- #trackbacks-list .comments -->

<?php endif /* if ( $ping_count ) */ ?>
<?php endif /* if ( $comments ) */ ?>
<?php if ( 'open' == $post->comment_status ) : ?>
				<div id="respond">
					<h3><?php _e('Comente') ?></h3>

<?php if ( get_option('comment_registration') && !$user_ID ) : ?>
					<p id="login-req"><?php printf(__('Você precisa estar <a href="%s" title="Log in">logado</a> para comentar.'),
					get_option('siteurl') . '/wp-login.php?redirect_to=' . get_permalink() ) ?></p>

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

<?php if ( $user_ID ) : ?>
							<p id="login"><?php printf(__('<span class="loggedin">Logado como <a href="%1$s" title="Logged in as %2$s">%2$s</a>.</span> <span class="logout"><a href="%3$s" title="Log out of this account">Sair?</a></span>'),
								get_option('siteurl') . '/wp-admin/profile.php',
								wp_specialchars($user_identity, true),
								get_option('siteurl') . '/wp-login.php?action=logout&redirect_to=' . get_permalink() ) ?></p>

<?php else : ?>

														<div class="form-label"><label for="author"><?php _e('Name') ?></label> <?php if ($req) _e('<span class="required">*</span>') ?></div>
							<div class="form-input"><input class="campos" id="author" name="author" type="text" value="<?php echo $comment_author ?>" size="30" maxlength="20" tabindex="3" /></div>

							<div class="form-label"><label for="email"><?php _e('Email') ?></label> <?php if ($req) _e('<span class="required">*</span>') ?></div>
							<div class="form-input"><input class="campos" id="email" name="email" type="text" value="<?php echo $comment_author_email ?>" size="30" maxlength="50" tabindex="4" /></div>

							<div class="form-label"><label for="url"><?php _e('Website') ?></label></div>
							<div class="form-input"><input class="campos" id="url" name="url" type="text" value="<?php echo $comment_author_url ?>" size="30" maxlength="50" tabindex="5" /></div>

<?php endif /* if ( $user_ID ) */ ?>

							<div class="form-label"><label for="comment"><?php _e('Comment') ?></label></div>
							<div class="form-textarea"><textarea class="campos" id="comment" name="comment" cols="50" rows="8" tabindex="6"></textarea>
						  </div>

							<div class="form-submit"><input class="botao" id="submit" name="submit" type="submit" value="<?php _e('Comentar') ?>" tabindex="7" accesskey="P" /><input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" /></div>

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

						</form><!-- #commentform -->
					</div><!-- .formcontainer -->
<?php endif /* if ( get_option('comment_registration') && !$user_ID ) */ ?>

				</div><!-- #respond -->
<?php endif /* if ( 'open' == $post->comment_status ) */ ?>

			</div><!-- #comments -->

Now your comments funcionality must be working on your WordPress site, but let’s say you want to change a little comments CSS. Here goes a example with the basic elements. Just put it on your style.css file and change the properties you want:
Agora sua funcionalidade de comentários deve estar funcionando em seu site WordPress, mas digamos que você quer mudar um pouco o CSS dos comentários. Aqui vai um exemplo com os elementos básicos. É só colocar no seu arquivo style.css e mudar as propriedades que quiser:

#comments #comments-list ol li{list-style:none;padding:5px 5px 3px 10px;background-color:#e1e4e8;margin-bottom:10px}
#comments #respond .formcontainer #commentform .form-label label{width:auto;padding-right:2px;}
#comments #respond .formcontainer #commentform .form-input input{width:330px;height:25px}
#comments #respond .formcontainer #commentform .form-textarea textarea{width:330px;height:155px}
#comments #respond .formcontainer #commentform .form-submit #submit{margin: 10px 0 0;}
#comments{clear:both;}
#comments #respond .formcontainer{margin-top:10px;}

Hope you find it useful.
Espero que achem útil.

Advertisements

,

2 Comments

Display WordPress Page Navigation on Category Pages – A Very Easy Way

You should also take a look on New Hack for Displaying a Category Menu on WordPress

Cassio, a friend of mine, asked me to show in a very easy way, how to display page navigation on category pages. So, here we go…
Cassio, um amigo meu, me pediu para mostrar um jeito muito fácil de exibir navegação de página em páginas de categoria. Então, lá vamos nós…

Here is the code to use before the loop.
Aqui está o código a ser usado antes do loop.

 <?
	// choose a category
	$catnam = 'newposts';
	// get the total count of the posts for the choosen category
	$totpst = wt_get_category_count($catnam);
	// the page navigation variable, and the setting to start at page 1
	$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
	// the total of registers to show on each page
	$showp = 10;
	// the query, with all parameters
	query_posts("category_name=$catnam&showposts=$showp&paged=$paged");                                 			 	
?>            

Now, let’s run the loop.
Agora vamos executar o loop.

 <?

        if (have_posts()) :
	   while (have_posts()) : the_post();
              echo get_the_content();
           endwhile;         
	else:
              echo "There are no posts";
	endif;	                                			 	
?>            

Finally, we display the page navigation.
Finalmente, exibimos a páginação.

 <?
	// if the total count of posts is greater than the total of registers to show 
        // on each page(if you want, you can delete this if and end if)
        if($totpst  >= $showp):
	   next_posts_link('< Previous Posts'); 
	   echo " - ";
	   previous_posts_link('Recent Posts >'); 
	endif;	                                			 	
?>            

Hope you find it useful, Cassio 🙂
Espero que você ache útil, Cassio 🙂

,

5 Comments

Displaying categories and subcategories “tree like” list on WordPress

Suppose you want to show a category / subcategory “tree like” list on a WordPress page that gets the posts from a certain “main” category.
Suponha que você quer mostrar uma “árvore” de categorias / subcategorias numa página WordPress que contém posts de uma certa categoria “principal”.

The following code, probably will be useful.
O código a seguir, provavelmente lhe será útil.

//# first of all, you need to get the category array,
//   and I did it, putting the line bellow inside the loop
$category = get_the_category(get_the_ID());

// once you have the category array, the rest of the code will work wherever you want on the page 

//# getting the main category of the page
$catid=$category[0]->category_parent;
if($catid==0){
  $catid=$category[0]->cat_ID;
}

//# now letz get the children categories of the main category
$categories = get_categories('child_of='.intval($catid)); 					 

foreach ($categories as $category) {
    //# check if it is a real parent category with subcategories
    if ($category->parent ==$catid):
        echo '<span class="category"><a href="">'.$category->cat_name.'</a></span>';
        //# here we go, getting the subcategories
        $subcategories=  get_categories('child_of='.intval($category->cat_ID));
        foreach ($subcategories as $subcategory) {
            echo '<span class="subcategory" style="padding-left:12px">';
            echo '<a href="">'.$subcategory->cat_name.'</a></span>';
        }
    endif;
}

8 Comments

%d bloggers like this: