Posts Tagged postaweek2011

Quick solution to display a menu like list of WordPress Custom Post Type Posts(with Custom Taxonomy) in case of emergency

Well, I was in a hurry, the customer needed to have his site working as soon as possible, and I had to display a menu like list of WordPress Custom Post Types working for three different languages, but I didn’t have time to think of a elegant way to make it work. So I’ve created this little hack, that checks the custom taxonomy for each post and uses a conditional to decide what happens as a quick solution, and I’m sharing with you, to use in a case of emergency ūüôā
Bem, eu estava com pressa, o cliente precisava ter seu dite funcionando o mais r√°pido poss√≠vel, e eu tinha que exibir uma lista tipo menu de Tipos de Posts Customizados WordPress funcionando para tr√™s diferentes idiomas, mas eu n√£o tinha tempo para pensar em um jeito elegante de fazer funcionar. Ent√£o criei este pequeno hack que verifica a taxonomia customizada para cada post e decide o que acontece usando uma condicional como uma solu√ß√£o r√°pida, e estou compartilhando com voc√™s, para usarem em caso de emerg√™ncia ūüôā

<ul class="submenu">
   <?
   // here it's the query for my custom post type - Movies 
   $querycp = array( 'post_type'=>'Movies','posts_per_page' => -1 );
   query_posts($querycp);
   while (have_posts()) : the_post();
   // here we check what's the post custom taxonomy, if it is the language we need
   $terms = get_the_terms(get_the_ID(), 'movies_cat');
    foreach ( $terms as $term ) {
        $catref = $term->slug;
    }
   //
     if($catref=="english"):
     ?>
      <li><a href="<?=get_permalink()?>" title=""><?=get_the_title()?></a></li>
     <?
     endif;
   endwhile;
    ?>
</ul>
Advertisements

,

2 Comments

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

WordPress Custom Taxonomy Page Example with Taxonomy Selection Function(select field)

Today I’ll show something quite useful. With just four steps, we will build a custom taxonomy page, that uses a function to build a select field(<select>), that reloads the custom taxonomy page retrieving posts based on the selected option(the selected taxonomy for a specific custom post type).
Hoje vou mostrar algo bastante √ļtil. Com apenas quatro passos, vamos construir uma p√°gina de taxonomia customizada, que usa uma fun√ß√£o para construir um campo select(<select>), que recarrega a p√°gina recuperando posts baseados na op√ß√£o selecionada(a taxonomia selecionada para um tipo de post customizado).

Step One:

First of all, we need to register a custom post type called video and a custom taxonomy called genre, as I show on my previous post.
Antes de mais nada, precisamos registrar um tipo de post customizado chamado video e uma taxonomia customizada chamada genre, como mostro em meu post anterior.

Step Two:

The function bellow builds a <select> field with options based on taxonomies registered for a specific custom post type. The code also brings a javascript function that redirects to the taxonomy page(taxonomy-genre.php on this example), where you can show the posts from a specific custom taxonomy. Put it on your functions.php file, on your theme directory.
A fun√ß√£o abaixo constr√≥i um campo <select> com op√ß√Ķes baseadas em taxonomias registradas para um tipo de post customizado espec√≠fico. O c√≥digo tamb√©m tr√°s uma fun√ß√£o javascript que redireciona √† p√°gina da taxonomia(taxonomy-genre.php neste exemplo), onde voc√™ pode mostrar os posts de uma taxonomia customizada espec√≠fica. Coloque ele no seu arquivo functions.php, no diret√≥rio de seu tema.

<?
function wp_selcstch_taxonomies( $args = '' ) {
	
	$defaults = array(			
		'taxonomy' 	=> 'category',		
  		'seltitle'	=> '',
		'selnamen'	=> '',
		'selidcss'	=> '' ,
		'baselink'	=> '', 
		'echo' => 1,
		'hide_empty'   => 0
	);

	$r = wp_parse_args( $args, $defaults );
	extract( $r );

	if ( !taxonomy_exists($taxonomy) )
		return false;
	
	if( isset( $r['seltitle']) && $r['seltitle']!=""):$idtlt =  $r['seltitle'];else:$idtlt =  '';endif;		
	if( isset( $r['selnamen']) && $r['selnamen']!=""):$idnam =  " name='".$r['selnamen']."' ";else:$idnam = '';endif;
	if( isset( $r['selidcss']) && $r['selidcss']!=""):$idcss =  " id='".$r['selidcss']."' ";else:$idcss = '';endif;	

	$categories = get_categories( $r );
	$swlink = false;
	$swchan = '';
	$output = '';

	// javascript function to redirect(reload) the page
	if( isset( $r['baselink']) && $r['baselink']!=""):
		$output .= '<script language="javascript">';
		$output .= 'function fgotxm(obj){';
		$output .= 'if(obj.options[obj.options.selectedIndex].value!=""){';
		$output .= 'window.location.href=obj.options[obj.options.selectedIndex].value;';
		$output .= '}';
		$output .= '}';
		$output .= '</script>';
		$swlink = true;
		$swchan = " onchange='fgotxm(this)'";
	endif;

	// html begin
	$output .= "<select".$idnam.$idcss.$swchan.">";
	if($idtlt!=""){
	$output .= "<option value=''>".$idtlt."</option>";;	
	}
	foreach ($categories as $cat):
		if($cat->category_nicename!=$taxonomy){
			if($swlink):$golnk =  " value='".$r['baselink']."/".$cat->slug."' ";else:$golnk = '';endif;
			$output .= "<option".$golnk.">".$cat->name."</option>";
		}
	endforeach;
	$output .= "</select>";
	
	if ( $echo )
		echo $output;
	else
		return $output;
}
?>

Step Three:

Now, let’s build a taxonomy page, called taxonomy-genre.php and save it on the theme directory.
Agora vamos construir uma página de taxonomia, chamada taxonomy-genre.php e salvá-la no diretório de seu tema.

<? 
// Let's get the term that was called by the url
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

// here we will pass some parameters for our function that builds the select
$taxonomy   = 'genre'; // the taxonomy slug
$seltitle	= 'Select a Option'; // the select title
$selnamen	= 'select_opt'; // the select name
$selidcss	= ''; // a css id for the select, if wanted
$baselink	= get_bloginfo('url') . "/".'genre'; // and our page base link
// the baselink is the workaround we use to make WordPress find the taxonomy page

$args = array(
  'taxonomy'     => $taxonomy ,
  'seltitle'	 => $seltitle ,
  'selnamen'	 => $selnamen ,
  'selidcss'	 => $selidcss,
  'baselink'	 => $baselink,
  'echo'	 => 0
);

// here we call the function that builds the select
$combotax = wp_selcstch_taxonomies( $args) ;

// and here we set two conditions based on the term asked on the url to build the query
//
// first we call all the genres(genre taxonomy) for the video custom post type 
// it will be used when the user calls http://yourdomain/genre/all/ on your browser 
if($term->slug=="all"){ 
	$querycp = array( 'post_type'=>'video','posts_per_page' => -1 );
}
// then we call a specific genre(genre taxonomy) for the video custom post type e.g. scifi 
// it will be used when the user calls http://yourdomain/genre/scifi/ on your browser 
else{
	$querycp = array( 'post_type'=>'video', 'genre' => $term->slug, 'posts_per_page' => -1 );	
}
?>
<html>
<body>
<head>
<title>Example</title>
</head>

<?=$combotax."<br>"; // let's display the combo ?>

<? 
// and build the loop
query_posts($querycp);
if (have_posts()) :
  while (have_posts()) : the_post();								  
    echo get_the_title()."<br>";
    echo get_the_content()."<br>";
  endwhile;
endif;
?>
</body>
</html>

Step Four:

Now you must go to wp-admin. On Videos menu, choose Genres and create a main genre called “all”, with slug “all”. Then you can add some child genres, something like “drama” with slug “drama”, “scifi” with slug “scifi”, etc(take a look on the picture).

Genres for videos

Click to open - genres for custom post type video


Agora voc√™ deve ir at√© o wp-admin. No menu Videos, escolha Genres e crie um gen√™ro principal chamado “all”, com slug “all”. Ent√£o voc√™ pode adicionar alguns gen√™ros filhos, algo como “drama” com slug “drama”, “scifi” com slug “scifi”, etc(d√™ uma olhada na figura).

Don’t forget to add some posts to each child genre to display on your custom taxonomy page. Last but not least, a important tip: after registering a custom taxonomy, go to wp-admin and simply visit the permalinks settings page. It flushes all WordPress permalink rules, so it will make your changes related to the taxonomy page work.
N√£o esque√ßa de adicionar alguns post para cada gen√™ro filho para mostrar em sua p√°gina de taxonomia customizada. Por √ļltimo, mas importante, uma dica: depois de registrar uma taxonomia customizada, v√° at√© o wp-admin e simplesmente visite a p√°gina de configura√ß√Ķes de permalinks. Isso faz com que suas regras de permalink sejam zeradas, fazendo suas mudan√ßas relacionadas √† p√°gina de taxonomia funcionar.

Hope you find this example useful.
Espero que voc√™ ache este exemplo √ļ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

Retrieving The Total Number of Posts from a Specific Custom Post Type WordPress Taxonomy

The function bellow can be used to retrieve the total number of posts from a specific custom post type taxonomy in WordPress sites. There are only two steps, supposing you’ve registered a custom post type video and a taxonomy genre as I show on a previous post.
A fun√ß√£o abaixo pode ser usada para retornar o n√ļmero total de posts de uma taxonomia espec√≠fica de um tipo de post customizado. S√£o apenas dois passos, supondo que voc√™ criou um tipo de post customizado ‘video’ e uma taxonomia ‘genre’ como eu mostro em um post anterior.

Step 1:

<?
// put this code on your functions.php file, on your theme directory
// the function use the custom post type registration and the taxonomy slug as parameters
function wt_get_custom_taxonomy_count($ptype,$pterm) {
	global $wpdb;
	$SQL  = "SELECT count(*) FROM $wpdb->posts posts, $wpdb->terms terms, $wpdb->term_relationships rels ";
	$SQL .= "WHERE posts.post_status = 'publish' ";
	$SQL .= "AND post_type = '".$ptype."' ";
	$SQL .= "AND posts.ID = rels.object_id ";
	if($pterm!=""):
	$SQL .= "AND terms.slug = '".$pterm."' ";
	endif;
	$SQL .= "AND terms.term_id = rels.term_taxonomy_id";
	return $wpdb->get_var($SQL);
}
?>

Step 2:

<?
// put this on the theme page where you want the info to show
echo wt_get_custom_taxonomy_count('video','genre');
?>

This code can be very useful to be used when you are working on a WordPress custom taxonomy page.
Este c√≥digo pode ser bastante √ļtil quando voc√™ est√° trabalhando em uma p√°gina de taxonomia customizada do WordPress.

,

Leave a comment

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

%d bloggers like this: