WordPress.org

Ready to get started?Download WordPress

Forums

Access the post's image from template? (5 posts)

  1. mark12b
    Member
    Posted 8 years ago #

    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.

  2. digory
    Member
    Posted 8 years ago #

    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)

  3. thesheep
    Member
    Posted 8 years ago #

    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:

    wp-content/uploads/myimage.gif

    or an absolute URL like this:

    http://www.mydomain.com/wp-content/uploads/myimage.gif

    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.

  4. thesheep
    Member
    Posted 8 years ago #

    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?

  5. moshu
    Member
    Posted 8 years ago #

    so that the image associated with each post is pulled in
    Why not to try this plugin?
    http://guff.szub.net/2006/02/09/post-image/

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.