Feb 11 2009

Auto inserted intro image on Wordpress

Today we are going to do some simple Wordpress programming. I would like to show how easy it is to get attachment from a post, in our case images, and display them how we want.

The idea is to display an image floated right at the beginning of each post without having to insert it into the WYSIWYG editor of  Wordpress.  The reason is tinyMCE doesn’t always show it how I want it and may add some useless code around the picture. The only thing you will have to do it upload the picture with wordpress built in feature and name it ‘thumbnail’.

upload

Attachments are saved like posts. They have a post title, id, post parent, etc…  So we are going to build a custom query to retrieve the attachment url.

$querystr = "
	SELECT wposts.ID
	FROM $wpdb->posts wposts
	WHERE wposts.post_title = 'thumbnail'
	AND wposts.post_type = 'attachment'
	AND wposts.post_parent = '".$post->ID."'
";

$id = $wpdb->get_results($querystr, ARRAY_A);

$url = wp_get_attachment_thumb_url($id[0]['ID']);

The function wp_get_attachment_thumb_url do what it is called: get the auto generated thumbnail of the picture you’ve uploaded. Now what happen if you haven’t uploaded any picture? I choose to display a default picture instead by adding an if statement at the end:

<?php $querystr = "
	SELECT wposts.ID
	FROM $wpdb->posts wposts
	WHERE wposts.post_title = 'thumbnail'
	AND wposts.post_type = 'attachment'
	AND wposts.post_parent = '".$post->ID."'
";

$id = $wpdb->get_results($querystr, ARRAY_A);

$url = wp_get_attachment_thumb_url($id[0]['ID']);

if(empty($url))
{
	$url = get_bloginfo('template_url').'/default.jpg';
}?>

<img src="<?php echo $url ?>" alt="<?php $post->post_title ?>" class="thumbnail" />

Now this code in The Loop would look like this (from default template index.php file):

<?php
/**
* @package WordPress
* @subpackage Default_Theme
*/

get_header(); ?>

<div id="content" class="narrowcolumn">

<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<div class="entry">
<?php
$querystr = "
SELECT wposts.ID
FROM $wpdb->posts wposts
WHERE wposts.post_title = 'thumbnail'
AND wposts.post_type = 'attachment'
AND wposts.post_parent = '".$post->ID."'
";

$id = $wpdb->get_results($querystr, ARRAY_A);

$url = wp_get_attachment_thumb_url($id[0]['ID']);
if(empty($url))
{
$url = get_bloginfo('template_url').'/default.jpg';
}
?>
<img src="<?php echo $url ?>" alt="<?php $post->post_title ?>" class="thumbnail" />
<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>

<p class="postmetadata"><?php the_tags('Tags: ', ', ', '<br />'); ?> Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>  <?php comments_popup_link('No Comments &#187;', '1 Comment &#187;', '% Comments &#187;'); ?></p>
</div>

<?php endwhile; ?>

<div class="navigation">
<div class="alignleft"><?php next_posts_link('&laquo; Older Entries') ?></div>
<div class="alignright"><?php previous_posts_link('Newer Entries &raquo;') ?></div>
</div>

<?php else : ?>

<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php get_search_form(); ?>

<?php endif; ?>

</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Now add some CSS to float the picture, add border, margin, etc…

Benoit Gilloz
Programmer, Research and Development

9 Responses to “Auto inserted intro image on Wordpress”

  1. [...] I wrote last week about automatically displaying a picture on each post with wordpress. Now I would like to expand a bit on the custom request and show how to pull a random picture from [...]

  2. Hi,

    Is there a way to adapt this to work on pages instead of posts? I’m trying to get it to show 3 images in a column down the right hand edge of the page.

    Thanks!
    Ben

  3. Yes, you can start from this code and adapt it a little so it displays more than one picture. Then I’ll let you figure out the css to get them down the side ;) . If you place the below code in the loop of the page.php file it should work.

    <?php
    $querystr = "
    SELECT *
    FROM $wpdb->posts wposts
    WHERE wposts.post_type = 'attachment'
    AND wposts.post_parent = '".$post->ID."'
    ";

    $id = $wpdb->get_results($querystr, ARRAY_A);

    foreach($id as $pic)
    {
    $url = wp_get_attachment_thumb_url($pic['ID']);
    if(empty($url))
    {
    $url = get_bloginfo('template_url').'/default.jpg';
    }
    ?>
    <img src="<?php echo $url ?>" alt="<?php $post->post_title ?>" class="thumbnail" />
    <?php
    }
    ?>

  4. Thanks for the help. Much appricated!

    Dropped the code in and its worked first time.

    It doesn’t quite work as I expected (that because I miss read it, not because of your code). I want to limit it to 3 or 4 images showing in the side column. I guess I need to limit the loop for that.

    I’d love to be able to re-order the images some how and also add images in to the main content of the page without having to add them to the sidebar. All a bit out side of what this is designed to do! I think I’m a bit to ambitious for my level of Wordpress knowledge!

    Again, Thanks for your help on this – your blog is bookmarked and tagged – I’ll be back to learn more!

    Cheers.

  5. No Worries Ben. To limit the number of attachments returned by the query (to 3 for example) the best way would be to add ‘LIMIT 3′ at the end of the query. Now to be able to add other pictures in the content without displaying them in the sidebar you could perhaps name them something like ‘name-sidebar’ and change the query to something like:

    SELECT *
    FROM $wpdb->posts wposts
    WHERE wposts.post_type = 'attachment'
    AND wposts.post_parent = '".$post->ID."'
    AND wposts.post_title LIKE "%-sidebar"
    LIMIT 3

    I have not tested this one so use at your own risks :p but it should work.

  6. You are a STAR! Thank you!

    I can’t believe its as easy as ‘LIMIT 3′. Do I feel stupid now :)

    AND wposts.post_title LIKE “%-sidebar” throws up “Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING”. I can see what you are doing – I guess the syntax isn’t right though. I’ve had a search for info on this to see how LIKE and % are used but as search terms they are a bit to vague! I figured % is a variable.

    Could you point me in the right direction on how to use LIKE or at least how they should work in this example?

    Sorry to be so demanding!

    Ben

  7. Oops, my bad, the LIKE should read:

    LIKE '%-sidebar'

    The double quotes must be replaced by simple quotes. With the double quote php sees it as a break in the string. The request uses % which is the wildcard in SQL.

    So the request does something like “get me everything from the table wposts that has a type of ‘attachment’, a post parent equal to the current post id and a title that look like ’something-sidebar’. Oh and just three of those please”.

    Hopefully this time it’s alright :)

  8. Thank you! Its working perfectly. I had actually tried that but it still generated an error code so I though I’d done it wrong, but I just needed to upload an image tagged correctly.

    Thank you for you patience and help – it is very much appricated.

    Hope one day I can return the favor (I suspect it won’t be WP related though! I can tell you all about design and print though!)

    Cheers,
    Ben

  9. Awesome, very happy that it worked at the end. Print is definitely an area I could use you help one day =)

Leave a Reply