Display WordPress Post List With Custom Size Thumbnails(the first image of each post)

This post moved to http://www.wpworking.com/general/display-wordpress-post-list-with-custom-size-thumbnails/


Maybe you will like to take a look on my Get Post List With Thumbnails plugin, wich is a evolution of the function bellow and you can configure and use as widget.

The function bellow, shows a list with posts and custom size thumbnails(for the post first image), linked to each post permalink. You can use it wherever you want, and you can choose a category(not required) and the number of posts(not required). Two simple steps:
A função abaixo mostra uma lista de posts com thumbnails de tamanho customizável(para a primeira imagem de cada post), linkados ao link permanente de cada post. Você pode usar onde quiser, e pode escolher uma categoria(não obrigatório) e o número de posts(não obrigatório). Dois passos simples:

1) Put this function on “functions.php” file, in your template folder:
1) Coloque esta função no arquivo “functions.php”, na pasta de seu template.

// display a list of posts with custom size thumbnails, using the post first image
function getPostList($categ='',$postnr=20){
	// $categ = category name - not required
	// $postnr = number of posts you want to display - not required
	$htmlcod .= "<div id='div_postlist' style='border:1px red solid'>"."\n";
	if (have_posts()) : 				
		global $post;
	    // here we check if the user has chosen a category
	      $strquery = "numberposts=".$postnr."&category_name=". $categ;				
	      $strquery =  "numberposts=".$postnr;
	    // here we get the posts
	    $myposts = get_posts($strquery);
	    // if we want, we can display the number of registers found
	    //echo sizeof($myposts);
		 // here we go in the loop
		foreach($myposts as $post) :				 	
                    // getting the first image of the post to make the thumb
                    $args = array(
                        'post_type' => 'attachment',
                        'numberposts' => -1,
                        'post_status' => null,
                        'post_parent' => $post->ID
                    $attachments = get_posts($args);
                    // here we set the variable for the attachment string
                    $imgsrc = "";
                    if ($attachments):
                        // here we take the first image and break the loop
                        foreach ($attachments as $attachment) {
                             // this brings the attachment array $imgobj = wp_get_attachment_image_src($attachment->ID);
                             // if you use the line obove, you can call $imgobj[0] to get the image source 
                            // you can set the thumbnail dimensions, here we use 40 x 40
                            $imgsrc = wp_get_attachment_image($attachment->ID, array(40,40), $icon = false);
                    // here we start to build the return html code
                        $htmlcod .= "<p><a href='". get_permalink()."' title='". get_the_title() ."'>";
                        $htmlcod .= get_the_time('d/m/Y')."-".get_the_title();
                        $htmlcod .= "</a></p>"."\n";	
                    // if the post has at least one image attached, we display it
                        $htmlcod .= "<p>";                                	
                        $htmlcod .= "<a href='". get_permalink() ."' title='". get_the_title() ."'>";
                        $htmlcod .= $imgsrc; 
                        $htmlcod .= "</a>"."\n";       
                        $htmlcod .= "</p>"."\n";															
			// here goes the message, if there is no results to display
			$htmlcod = "<div>"."\n";
			$htmlcod .= "<p>No registers found.</p>"."\n";								
			$htmlcod .= "</div>"."\n";
        $htmlcod .= "</div>";
	return $htmlcod;

2) Call the function wherever you want:
2) Chame a função, onde quiser.

// e.g. - no category, twenty(20) posts 
<? echo getPostList('',20); ?>


// e.g. - 'musicposts' category name, no number of posts, but the function uses 20 as default
<? echo getPostList('musicposts');  ?>


 // e.g. - 'gameposts' category name, no number of posts, 5 posts
<? echo getPostList('gameposts',5); ?>

Hope you find it useful.

, , ,

  1. #1 by carina on March 16, 2011 - 4:47 pm

    Estou montando esse site e quero fazer uma lista de arquivos com thumbnails,title, um pouco de texto e read more,
    Mas eu não quero colocar no sidebar, então eu não queria como widget.
    Mas seguindo colocando na página functions não está funcionando.
    Tem como eu fazer isso?

  2. #2 by Alvaro Neto on March 17, 2011 - 4:08 pm

    Oi Carina, você tem que colocar o indicado no passo 1 no arquivo functions e depois chamar(como exposto no passo 2) em uma página php. Por favor me mostra ou envia para alvaron8@gmail.com o seu código php, da página onde está chamando que vejo como posso te ajudar.

  3. #3 by volleronline on April 1, 2011 - 4:07 pm

    How do I edit the code to make it display posts in ASC order?

    • #4 by Alvaro Neto on April 1, 2011 - 4:17 pm

      Try change $strquery = “numberposts=”.$postnr; for $strquery = “numberposts=”.$postnr.”&orderby=’post_date’&order=’ASC'”;

      It will come in the next version, you can take a look on http://codex.wordpress.org/Template_Tags/get_posts to know all the parameters for “get_posts”.

      Best Regards.

  4. #5 by domdeez on April 11, 2011 - 8:00 pm

    How can you you assign a default graphic for when there is no image in a post, but you want to keep the format intact?

    • #6 by Alvaro Neto on April 11, 2011 - 8:21 pm

      Hi Domdeez, right now, you have to use one of this workarounds: 1) Put images on all posts; 2) Set the same category on all the posts you want to display with the plugin and put this category slug on the widget configuration, on wp-admin. On the next version, there will be a option to choose a default graphic. Best regards.

  5. #7 by Yann on April 20, 2011 - 9:53 am

    Hi Alvaro!

    I tried to use this code and something happened :
    I pasted the first part at the bottom of the functions.php, saved it, and since then, every time I refresh a page in the admin dashboard, I gota blank page with an error statement.
    Now i cannot login to my admin area anymore : this is what I get :

    Warning: Cannot modify header information – headers already sent by (output started at /home/almondp1/public_html/blog/wp-content/themes/atahualpa_ol/functions.php:939) in /home/almondp1/public_html/blog/wp-includes/pluggable.php on line 897

    If you have an idea of how to approach this I would be grateful 🙂

    • #8 by Alvaro Neto on April 20, 2011 - 12:33 pm

      Hey Yann. To help you, I need to take a look on your functions.php file. The problem on your case is that functions.php is sending info to headers, something that my code don’t do. Send me please at least the line 939 of your functions.php . My email is alvaron8@gmail.com . I think that the problem is not related to my code. You can also comment the functions.php line that causes the error and try to upload the file.

      • #9 by Yann on April 20, 2011 - 8:34 pm

        Ok, line 939 was an empty one : because I didn’t see any changes after pasting part 1 in function.php, I got cold feet and erased it, but apparently that empty line stayed there and caused a big bagunca..:) anyway I simply erased it & its fixed now, so thank you.
        Now that I’ve already bothered you with this, can I ask you where do I paste part 2 if i want to have a list of posts on specific static pages (can it be used more than once ?).

      • #10 by Alvaro Neto on April 20, 2011 - 9:12 pm

        Yann, first, good to know everything is fine with your theme. You can put one of the three examples for the part 2 anywhere you want on your theme. Suppose you are using twentyten theme, you could paste the code on sidebar.php and you can use it as many times as you want.

  6. #11 by Karl on May 26, 2011 - 9:46 am

    Oi Alvaro
    tem alguma possibilidade de usar a imagen definida em um custom field “Thumbnail”?
    Uso o thumbnail porque as imagens teem de estar em outro servidor

    • #12 by Alvaro Neto on June 8, 2011 - 12:05 pm

      Karl, teoricamente existe a possibilidade sim. Você poderia armazenar o endereço absoluto da imagem neste campo e retornar ele na tag html que chama a imagem na página de seu tema.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: