Support » Fixing WordPress » Access the post’s image from template?

  • In WP2.0, I have uploaded an image using the new file upload area. I see how to insert the image into the post, but how do I reference it in the template? The goal is to add a template tag to single.php, so that the image associated with each post is pulled in, bit in a different place than the post text.

    I tried adding a custom field with the name of the image, but the file upload thing tucks the images into dated subfolders, so I can’t access them using the same path for all. I have also tried accessing the image using the _wp_attached_file custom field (from the custom fields popup menu), but with no success.

    I have seen it mentioned that uploaded images are treated internally as sub-posts, but I can’t find any documentation for how this works.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You can get the image file location with:
    $img = get_post_meta($id, '_wp_attached_file', 1);

    The $id there is for the image, which is not the post ID. Each image has an entry in posts, which has the post’s ID you uploaded it to under post_parent.

    You can get this with:
    $id = $wpdb->get_results("select ID from $wpdb->posts where post_parent = $post->ID"); (untested; this could be an array)

    Yes, you will need to use $wpdb->get_var() instead of get_results(), since you only want a single value (the ID).

    I’m trying this now and I get the image location OK, but it is coming out as a URL relative to the root of the server (ie /my-hosting-account/www/wp-content/uploads/myimage.gif). So of course the image does not display. I want either a relative URL like this:


    or an absolute URL like this:

    I could just strip off the first bit using PHP, but that wouldn’t be very portable. WP itself must do this in the ‘write posts’ bit of the admin section as the URLs are correct when inserted into the body of a post.

    Except that you shouldn’t use get_var if there might be more than one image associated with a post. Then I guess you would want to use get_results() afterall.

    Apparently this returns an array of objects. Anyone know how to break out the image ids from these objects?

    so that the image associated with each post is pulled in
    Why not to try this plugin?

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Access the post’s image from template?’ is closed to new replies.