0

I am not a WordPress expert and need your support. Is there a way to create a button just like Set featured image but that button will allow us to attach an image to a post (from gallery) as a meta value? I am aware of custom meta boxes and manual upload of media but is there any possibility to avoid custom upload? I expect to duplicate the Set featured image functionality for a different purpose, i.e. to set a post header image, is there any possibility? Any help will be highly appreciated. Please ensure that featured image itself is being used for a different purpose and I am not willing to use it as the post header image.

1 Answer 1

0

The simplest way is to use the built-in custom fields. If you don't see them by default, while you're editing a Post/Page/CPT, choose "Screen Options" at the top right of the screen and check the "Custom Fields" box. Then scroll down through the editor until you see the Custom Fields box. Decide what you want to call your field, something unique with perhaps a prefix - like wpse_second_image - that you'll remember to use each time in the "name" field. You can then go to the media library, find the image you want, and copy and paste the URL into the "value" field.

Once your images are set, you'll probably want a fallback image in case you forget to set it or mis-type the field name. Something simple like this will do:

<?php
// make sure the Post object is available
global $post;
// get the "wpse_second_image" custom field for this Post
$second_image = get_post_meta($post->ID, 'wpse_second_image', true);
// if we found an image
if($second_image) {
    echo "<img src=\"$second_image\" />";
// if we didn't find an image, use a fallback
} else {
    echo "<img src=\"/path/to/fallback/image.jpg\" />";
}
?>

You'll put this wherever you want the image to appear in your theme. Sounds like header.php in a child theme may be appropriate for your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.