Posts Tagged basics

How to reset queries on WordPress

Sometimes you may want to reset WordPress queries, when you are working on a page that displays data from posts of different categories mixed with custom post types, for example(two or more queries on the same page).
Às vezes, talvez você queira resetar suas queries WordPress, quando você está trabalhando em uma página que exibe informações de posts de diferentes categorias misturados à tipos de posts customizados, por exemplo(duas ou mais queries na mesma página).

In this case, all you have todo is use wp_reset_query(); after each loop.
Neste caso, tudo que você deve fazer é usar wp_reset_query(); depois de cada loop.

If you have any doubt, just check the Codex.
Se você tiver alguma dúvida, verifique Codex.

,

Leave a comment

How to Stop WordPress Editor From Removing Break Tags <p> and <br />

If you are experiencing problems with the <p> and <br /> tags on your WordPress site, if they are automatically being removed from your posts causing spacing issues, there’s a simple workaround to deal with it.
Se você está enfrentando problemas com as tags <p> and <br /> no seu site WordPress, se elas estão sendo removidas automaticamente de seus posts causando dificuldades no espaçamento, há um jeito simples de lidar com isso.

Download and install the WordPress Plugin TinyMCE Advanced. After that, go to Settings / TinyMCE Advanced / Advanced and check / click the options marked on the picture bellow. WordPress will not ignore anymore the break tags <p> and <br />.
Baixe e instale o Plugin WordPress TinyMCE Advanced. Depois disso, vá até Configurações / TinyMCE Advanced / Advanced e marque / clique as opções assinaladas na figura abaixo. O WordPress não vai mais ignorar as tags de quebra <p> and <br />.

Hope you find this tip useful 😉
Espero que você ache esta dica útil 😉

,

Leave a comment

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.

,

2 Comments

Building a WordPress Rewrite Rule(Passing and Receiveing Parameters Using Permalink Url)

When you are working with WordPress, sometimes you may need to pass parameters to a page where you want to display posts data using the permalink url structure, e.g. http://yoursite/yourpage/2011/03/ where 2011 is the value for a year variable and 03 is the value for a month variable.
Quando você está trabalhando com WordPress, às vezes você pode precisar passar parâmetros para uma página onde quer exibir dados de posts usando a estrutura de url de permalinks, por exemplo, http://yoursite/yourpage/2011/03/ onde 2011 é o valor para uma variável de ano e 03 é o valor para uma variável de mês.

So, let’s take a look on the code.
Então, vamos dar uma olhada no código.

<?
// here we register the variables that will be used as parameters on the url
function add_my_var($public_query_vars) {
    $public_query_vars[] = 'yvar'; // year
    $public_query_vars[] = 'mvar'; // month
    return $public_query_vars;
}
add_filter('query_vars', 'add_my_var');

// building the rewrite rules, for the two parameters
function do_rewrite() {
     add_rewrite_rule('(yourpage)/[/]?([0-9]*)[/]?([0-9]*)$', 'index.php?pagename=yourpage&yvar=$matches[2]&mvar=$matches[3]','top');
}
add_action('init', 'do_rewrite');
?>

Now you are able to open a url like http://yoursite/yourpage/2011/03/, receiveing and printing some parameters. Here goes the code for printing the parameters on yourpage page.
Agora você é capaz de abrir uma url como http://yoursite/yourpage/2011/03/, recebendo e imprimindo alguns parâmetros. Aqui vai o código para imprimir os parâmetros na página yourpage

<?
echo "year:" .get_query_var( 'yvar' ) ."<br>";
echo "month: " .get_query_var( 'mvar' ) ."<br>";
echo "page :" .get_query_var('paged') ."<br>";
?>

There’s a important tip. After registering or changing any rewrite rule, go to wp-admin and simply visit the permalink settings page. It flushes all rules, so it will make your changes work 😉
Há uma dica importante. Depois de registrar ou mudar qualquer regra rewrite, vá até o wp-admin e simplesmente visite a página de configurações de permalink. Ela zera todas as regras, então isso vai fazer suas mudanças funcionar 😉

For further info, visit the Codex.
Para maiores informações, visite o Codex.

,

Leave a comment

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

Inside The Database: WordPress posts, categories, media and relationships

There is a few good basic things you’d probably like to know when you are working with WordPress, and need to get more familiar with the WordPress database.
Há algumas coisas básicas que você provavelmente gostaria de saber quando está trabalhando com WordPress e precisa se tornar mais familiarizado com a base de dados WordPress.

The table (1) wp_posts stores all the main post information, like title, content and type, where you can check if it is a post or a page.
A tabela (1) wp_posts armazena as informações principais dos posts, como título, conteúdo e tipo, onde você pode verificar se é um post ou página.

(2) wp_postmeta stores things like the reference information for the post attachments(media) and their properties, but also the slugs and values for the custom fields, and other relevant information, like the page templates information.
(2) wp_postmeta armazena coisas como as informações de referência para os anexos dos posts(mídia) e suas propriedades, mas também os apelidos e valores de campos customizados e outras informações relevantes, como informações dos templates de página.

On (3) wp_terms you will find your post and page categories.
Em (3) wp_terms você encontrará as categorias de seus posts e páginas.

(4) wp_term_taxonomy stores the category hierarchy, which is defined by the ‘parent’ column.
(4) wp_term_taxonomy armazena a hierarquia das categorias, a qual é definida pela coluna ‘parent’.

(5) wp_term_relationships deals with posts, pages and categories, relating it. The ‘object_id’ column refers to posts and pages(related to the ‘id’ column from ‘wp_posts’ table) and the ‘term_taxonomy_id’ column refers to their categories(related to the ‘term_id’ column from ‘wp_terms’).
(5) wp_term_relationship lida com os posts, páginas e categorias, relacionando-os. A coluna ‘object_id’ se refere a posts e páginas(relacionada à coluna ‘id’ da tabela ‘wp_posts’) e a coluna ‘term_taxonomy_id’ se refere às suas catagorias(relacionada à coluna ‘term_id’ da tabela ‘wp_terms’).

For further information, check the full WordPress Database diagram, on WordPress Codex.
Para maiores informações, veja o diagrama completo daBase de Dados WordPress, on WordPress Codex

,

Leave a comment

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