Skip to content

Instantly share code, notes, and snippets.

@SubZane
Created August 23, 2012 14:38
Show Gist options
  • Save SubZane/3437250 to your computer and use it in GitHub Desktop.
Save SubZane/3437250 to your computer and use it in GitHub Desktop.
WordPress: Image Custom Meta Property
add_action( 'add_meta_boxes', 'custom_meta_boxes' );
add_action( 'save_post', 'ExtraImageProperty_save' );
function custom_meta_boxes() {
add_meta_box('ExtraImageProperty', 'Extra Image Property', 'ExtraImageProperty', 'page');
}
function ExtraImageProperty() {
global $post;
$extra_image_url = get_post_meta($post->ID, 'extra_image_url', true);
wp_nonce_field( plugin_basename( __FILE__ ), 'ExtraImageProperty_wpnonce_name' );
?>
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function() {
var image;
jQuery('#upload_image_button').click(function() {
tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');
return false;
});
jQuery('#remove_image_button').click(function() {
jQuery('#extra_image_url').val("");
jQuery('#image_display').toggle();
jQuery('#upload_image_button').toggle();
jQuery('#remove_image_button').toggle();
});
window.send_to_editor = function(html) {
img = jQuery('img',html);
jQuery('#extra_image_url').val(img.attr('src'));
jQuery('#image_display').attr("src",img.attr('src'));
jQuery('#image_display').toggle();
jQuery('#upload_image_button').toggle();
jQuery('#remove_image_button').toggle();
tb_remove();
}
});
</script>
<?php
?>
<input id="extra_image_url" name="extra_image_url" type="hidden" value="<?php echo $extra_image_url?>" />
<img <?php if (empty($extra_image_url)) echo 'style="display:none"' ?> id="image_display" src="<?php echo $extra_image_url?>" width="266" alt="" />
<p><a <?php if (!empty($extra_image_url)) echo 'style="display:none"' ?> title="Set extra image" id="upload_image_button" href="#" />Set extra image</a></p>
<p><a <?php if (empty($extra_image_url)) echo 'style="display:none"' ?> title="Remove extra image" id="remove_image_button" href="#" />Remove extra image</a></p>
<?php
}
function ExtraImageProperty_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['ExtraImageProperty_wpnonce_name'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
update_custom_meta($post_id, $_POST['extra_image_url'], 'extra_image_url');
}
function update_custom_meta($postID, $newvalue, $field_name) {
if (!get_post_meta($postID, $field_name)) {
add_post_meta($postID, $field_name, $newvalue);
} else {
update_post_meta($postID, $field_name, $newvalue);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment