wordpressimagecustom-field-type

How would you recommend adding an image as a custom field in WordPress?


I need to add an image to each page in WordPress. I don't wish to insert it using the WYSIWYG editor, I just need the url as a custom field, which I later use in the template.

I tried using the CFI plugin (Custom Field Images), and I hacked my way into getting it to work with the rest of my plugins, but then I moved the site to the production server and CFI just didn't work for some reason.

I can't seem to find any other plugin that just lets you pick an image from the library and add it as a custom field.

I've downgraded to the point where I'm willing to manually enter all the URLs into each and every page. but before I do, I thought I'd check here.

Can anyone tell me what's the easiest, best way to add images as custom fields in WordPress (2.7.1 if it matters)?


Solution

  • In our WordPress template, each post generally only has one image 'attached', which is displayed outside the posts' (textual) content.

    I upload the file using the edit posts' media uploader, never insert it into the post like JoshJordan above, then retrieve the image using a bit of code in the right place in my template file.

    This would also work if you're using more than one image in your post, eg. in your post content. As long as you keep the image used as the 'main' post image as the first image (remember you can re-order images in your posts' image library by dragging them up and down), you're able to call it anywhere in your template file by using something like this:

    <?php
    $img_id   = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts where post_parent = %d and (post_mime_type = 'image/jpeg' OR post_mime_type = 'image/gif') and post_type = 'attachment'", $post->ID ) );
    $img_html = wp_get_attachment_image( $img_id, 'thumbnail' );
    
    if ( ! empty( $img_html ) ) {
        echo $img_html;
    }
    ?>
    

    No need for copying and pasting image urls.