ブログ

BLOG

CATEGORY

投稿用のカスタムフィールドを自作して画像を追加できるようにする。

画像が追加できるカスタムフィールドの作成

今まではSmart custom field などを使用して、カスタムフィールドを作成していたが、画像が追加できるものを自作する必要があった為、色々調べたところそれっぽいものが出来たのでメモ。

function.php への記述

/////////////////////// メタボックスの追加と保存 ///////////////////////
add_action("admin_init", "metaboxs_init");
function metaboxs_init(){ // 投稿編集画面にメタボックスを追加する
add_meta_box( 'myupload', 'アイテム画像', 'myupload_postmeta', 'post', 'side','high' ); // ポジションはsideが推奨です
add_action('save_post', 'save_myupload_postmeta');
}
/////////////////////// メタボックス(画像アップロード用) ///////////////////////
function myupload_postmeta(){ //投稿ページに表示されるカスタムフィールド
global $post;
$post_id = $post->ID;
$myupload_images = get_post_meta( $post_id, 'myupload_images', true );
if($myupload_images){
foreach( $myupload_images as $key => $img_id ){
$thumb_src = wp_get_attachment_image_src ($img_id,'thumbnail');
if ( empty ($thumb_src[0]) ){ //画像が存在しない空IDを強制的に取り除く
delete_post_meta( $post_id, 'myupload_images', $img_id );
} else {
$myupload_li.=
"\t".'<li class="img" id="img_'.$img_id.'">'."\n".
"\t\t".'<span class="img_wrap">'."\n".
"\t\t\t".'<a href="#" class="myupload_images_remove" title="画像を削除する"></a>'."\n".
"\t\t\t".'<img src="'.$thumb_src[0].'"/>'."\n".
"\t\t\t".'<input type="hidden" name="myupload_images[]" value="'.$img_id.'" />'."\n".
"\t\t".'</span>'."\n".
"\t".'</li>'."\n";
}
}
}
?>
<style type="text/css">
#myupload_images { display:block; clear:both; list-style-type: none; }
#myupload_images:after { content:"."; display:block; height:0; clear:both; visibility:hidden; }
#myupload_images li { display:block; width:100%; margin:0; padding:5px 0; text-align:center; }
#myupload_images li span.img_wrap { display:inline-block; margin:0; height:auto; width:auto; padding:4px; position:relative; background:#ccc; }
#myupload_images li span img { margin:0; padding:0; max-height: 160px; width:auto; vertical-align:text-bottom; }
#myupload_images li span input { display:none; }
#myupload_images li span a.myupload_images_remove { position:absolute; top:-8px; right:-8px; height:32px; width:32px; text-align:center; vertical-align:middle; background:#ccc; border-radius:50%; }
#myupload_images li span a.myupload_images_remove:before { content:'×'; display:inline-block; text-decoration:none; width:1em; margin-right:.2em; text-align:center; font-size:20px; line-height:20px; padding:6px; color:#fff; font-weight:bold; }
#myupload_images li span a.myupload_images_remove:hover { background:#aaa; }
#myupload_buttons a, #myupload_buttons input { padding:10px 15px; height:40px; line-height:20px; font-weight:bold; text-align:center; }
</style>
<div id="myupload_buttons">
<a id="myupload_media" type="button" class="button" title="画像を追加">アイテム画像の追加</a>
<input type="submit" name="save" id="save2" class="button" value="更新" />
<p>※ ×アイコンから消したい場合は、先に「更新」を押す。</p>
</div>
<ul id="myupload_images">
<?php echo $myupload_li; ?>
</ul>
<input type="hidden" name="myupload_postmeta_nonce" value="<?php echo wp_create_nonce(basename(__FILE__)); ?>" />
<script type="text/javascript">
jQuery( function(){
var custom_uploader;
jQuery('#myupload_media').click(function(e) {
e.preventDefault();
if (custom_uploader) {
custom_uploader.open();
return;
}
custom_uploader = wp.media({
title: _wpMediaViewsL10n.mediaLibraryTitle,
library: {
type: 'image'
},
button: {
text: '画像を選択'
},
multiple: true, // falseのとき画像選択は一つのみ可能
frame: 'select', // select | post. selectは左のnavを取り除く指定
editing: false,
});
custom_uploader.on('ready', function() {
// jQuery('select.attachment-filters [value="uploaded"]').attr( 'selected', true ).parent().trigger('change');
//「この投稿への画像」をデフォルト表示 不要ならコメントアウト
});
custom_uploader.on('select', function() {
var images = custom_uploader.state().get('selection'),
ex_ul = jQuery('#myupload_images'),
ex_id = 0,
array_ids = [];
if ( ex_ul[0] ){ //すでに登録されている画像を配列に格納
ex_ul.children('li').each( function( ){
ex_id = Number(jQuery(this).attr( 'id' ).slice(4));
array_ids.push( ex_id );
});
}
console.log(images);
images.each(function( file ){
new_id = file.toJSON().id;
if ( jQuery.inArray( new_id, array_ids ) > -1 ){ //投稿編集画面のリストに重複している場合、削除
ex_ul.find('li#img_'+ new_id).remove();
}
ex_ul.append('<li class="img" id=img_'+ new_id +'></li>').find('li:last').append(
'<span class="img_wrap">' +
'<a href="#" class="myupload_images_remove" title="画像を削除する"></a>' +
'<img src="'+file.attributes.sizes.thumbnail.url+'" />' +
'<input type="hidden" name="myupload_images[]" value="'+ new_id +'" />' +
'</span>'
);
});
});
custom_uploader.open();
});
jQuery( ".myupload_images_remove" ).on( 'click', function( e ) {
e.preventDefault();
e.stopPropagation();
img_obj = jQuery(this).parents('li.img').remove();
});
jQuery( "#myupload_images" ).sortable({
axis : 'y',
cursor : "move",
tolerance : "pointer",
opacity: 0.6
});
});
</script>
<?php }
/*データ更新時の保存*/
function save_myupload_postmeta( $post_id ){
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id; // 自動保存ルーチンの時は何もしない
if (!wp_verify_nonce($_POST['myupload_postmeta_nonce'], basename(__FILE__)))
return $post_id; // wp-nonceチェック
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) ) // パーミッションチェック
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ) ) // パーミッションチェック
return $post_id;
}
$new_images = isset($_POST['myupload_images']) ? $_POST['myupload_images']: null; //POSTされたデータ
$ex_images = get_post_meta( $post_id, 'myupload_images', true ); //DBのデータ
if ( $ex_images !== $new_images ){
if ( $new_images ){
update_post_meta( $post_id, 'myupload_images', $new_images ); // アップデート
} else {
delete_post_meta( $post_id, 'myupload_images', $ex_images );
}
}
}

single.phpに画像を出力させる記述

$custom_img_id = get_post_meta( $post->ID, 'myupload_images', true );
foreach( $custom_img_id as $key => $img_id ){
$custom_img[] = wp_get_attachment_image_src ($img_id,'full');
}
foreach( $custom_img as $custom ){
echo '<img src="'.$custom[0].'" width="" height="" alt=""/>';
}
$custom_img_id = get_post_meta( $post->ID, 'myupload_images', true );

参考サイト:
http://techblog.55w.jp/2014042400873/