Archive for January, 2011

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 🙂

Advertisements

,

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

YouTube/Photos Thumbnails on WordPress Similar Posts Plugin List

If you are working with “Similar Posts” plugin, and videos / images on your posts, maybe you would like to display a post thumbnail for each post on your related posts list.
Se você está trabalhando com o plugin WordPress “Similar Posts”, e vídeos / imagens em seus posts, talvez você gostasse de exibir um thumbnail de cada post em sua lista de posts relacionados.

There are three very simple steps.
São três passos muito simples.

1) First of all, take a look on this post, where I talk about my YouTube Thumbnails workaround on WordPress.
Primeiramente, dê uma olhada no post em que falo sobre minha solução para thumbnails do YouTube no WordPress.

2) Go to wp-admin/settings and on “Similar Posts” Output/Output template, you will paste the code from the next step.
Vá até wp-admin/configurações e em “Similar Posts” Output/Output template, você colará o código do próximo passo.

3) Then you can use my workaround, and the code bellow, together, to display a list of similar posts, with images of your posts(photo, YouTube thumbnails) and a default image for those posts without media.
Então você pode usar minha solução, e o código abaixo, juntos, para exibir uma lista de posts similares com imagens do seu post(thumbnails de fotos, do YouTube) e uma imagem padrão para aqueles posts sem mídia.

<div>
<span><a href={url} title={title}>
<img src={imagesrc} alt={title} {php:if(strval({imagesrc})==""):echo "style='display:none;'";endif;}>
{php:$videolnk ="";$videolnk = get_post_meta({postid}, 'link_video', true);$videolnk = str_replace('http://www.youtube.com/watch?v=','http://img.youtube.com/vi/',$videolnk); if($videolnk!=''):$videolnk = $videolnk.'/2.jpg';endif;if(strval({imagesrc})==""&& $videolnk!=""):echo "<img alt='videolnk' src=$videolnk width=150>";endif;if(strval({imagesrc})==""&& $videolnk==""):echo "<img src='yourdefaultthumbnailimage'>";endif;}
</a></span>
{link}
</div>

It uses PHP + “Similar Posts” custom tags to control and display the thumbnails.
Ele usa PHP + mais tags customizadas do “Similar Posts”, para controlar e exibir os thumbnails.

I hope you find this useful. Good luck!
Espero que você ache útil. Boa Sorte!

, ,

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

WP e-Commerce List Products and Images Hack

Important note: It works only for WP-ecommerce 3.6. For later versions, WP-ecommerce database has changed, so you will need the new hack.

You should also take a look on my WP e-Commerce Product Showroom Plugin, a configurable widget and a evolution of the code bellow.

If you are working with WP e-Commerce Plugin, with the code bellow, you will be able to get a kind of product list, with images, anywhere you want on your site.

Just change your database information, and the LIMIT on mysqlquery, and no more stress…

Good look, may the force be with you.

<?
   $conn = mysql_connect("SERVER", "USER", "PASS"); 
    mysql_select_db("DATABASE") or die ("Could not select database" . mysql_error());
    // if you are note sure about the value of $wp_table_prefix, perform a search for this
    // text on your site, the usual value is "wp_" or something
    $sql = "SELECT products.id,products.name,products.description,products.image,product_category.category_id ";
    $sql .= "FROM ".$wp_table_prefix."wpsc_product_list AS products ";
    $sql .= "LEFT JOIN ".$wp_table_prefix."wpsc_item_category_assoc AS product_category ON ";
    $sql .= "products.id=product_category.product_id ";
    $sql .= "WHERE products.publish=1 AND products.active=1 ORDER BY products.name LIMIT 3";
    $qry = mysql_query($sql);
    $nrt = mysql_num_rows($qry);
    while($rs = mysql_fetch_array($qry)):          
?>
                <div>
                    <ul>
                        <li><a href="<?php echo wpsc_product_url($rs[0]); ?>">
                        <img src="index.php?image_id={<?=$rs[3]?>}"></a>
                        <a href="<?php echo wpsc_product_url($rs[0]); ?>"><?=$rs[1];?></a></li>   
                        <li><?=calculate_product_price($rs[0]);?></li>                   
                               
                    </ul>                    
                </div>
<?
	endwhile;     
?>

,

7 Comments

%d bloggers like this: