Add a media button for custom meta box image for a page or post

hello fellos,

As i have been searching for adding an image from wordpress media uploader to my page. It was really tough search to find a right solution with working script.

Here is the script that worked for me. Just paste it on functions.php and do the required changes.

/**
* Create Area icon image metabox
*/

function lacuna2_case_study_bg( $post ) {
wp_nonce_field( ‘case_study_bg_submit’, ‘case_study_bg_nonce’ );
$lacuna2_stored_meta = get_post_meta( $post->ID ); ?>

<p>
<label for=”case-study-bg” class=”lacuna2-row-title”>Practice Area Icon Image</label>
<img style=”max-width:200px;height:auto;” id=”meta-image-preview” src=”<?php if ( isset ( $lacuna2_stored_meta[‘meta-image’] ) ){ echo $lacuna2_stored_meta[‘meta-image’][0]; } ?>” />
<input type=”text” name=”meta-image” id=”meta-image” class=”meta_image” value=”<?php if ( isset ( $lacuna2_stored_meta[‘meta-image’] ) ){ echo $lacuna2_stored_meta[‘meta-image’][0]; } ?>” />
<input type=”button” id=”meta-image-button” class=”button” value=”Choose or Upload an Image” />
</p>
<script>
jQuery(‘#meta-image-button’).click(function() {

var send_attachment_bkp = wp.media.editor.send.attachment;

wp.media.editor.send.attachment = function(props, attachment) {

jQuery(‘#meta-image’).val(attachment.url);
jQuery(‘#meta-image-preview’).attr(‘src’,attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}

wp.media.editor.open();

return false;
});
</script>
<?php

}

/**
* Add Case Study background image metabox to the back end of Case Study posts
*/

function lacuna2_add_meta_boxes() {
add_meta_box( ‘case-study-bg’, ‘Case Study background image’, ‘lacuna2_case_study_bg’, ‘page’, ‘side’, ‘low’ );
}
add_action( ‘add_meta_boxes’, ‘lacuna2_add_meta_boxes’ );

/**
* Save background image metabox for Case Study posts
*/

function save_case_study_bg_meta_box( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ ‘case_study_bg_nonce’ ] ) && wp_verify_nonce( $_POST[ ‘case_study_bg_nonce’ ], ‘case_study_bg_submit’ ) ) ? ‘true’ : ‘false’;

// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}

// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ ‘meta-image’ ] ) ) {
update_post_meta( $post_id, ‘meta-image’, $_POST[ ‘meta-image’ ] );
}
}

add_action( ‘save_post’, ‘save_case_study_bg_meta_box’ );

 

Leave a Comment