2017.03.17WEB - WordPress

自前カスタムフィールドでメディアのアップロード

こういうやつ。

ちなみに、これはポジションはsideです。

こちらのコードを使用させて頂いてます。
メディアアップローダーを使ってカスタムフィールドに画像を登録する。
wordpressの投稿画面にメディアアップローダー付きのカスタムフィールドを設置する。

jQueryのバージョンが上がって、.live()が使用できないので改変したくらいなんですが。
jQuery UIでsortableあたりをどうにかしたいなぁ。

<?php
/*------------------------------------------
 add_metabox
  ------------------------------------------*/
add_action("admin_init", "metaboxs_init");
function metaboxs_init(){
    $post_types = 'post'; // 複数のカスタム投稿の場合は配列で 例:array('post', 'news')
    add_meta_box('myupload', '画像アップロード', 'myupload_postmeta', $post_types, 'normal', 'high'); // ポジションはnormal side advancedから好きなのを
    add_action('save_post', 'save_myuploads_postmeta');
}

/*------------------------------------------
 myupload_postmeta
  ------------------------------------------*/
function myupload_postmeta(){
    global $post;
    $post_id = $post->ID;
    $myupload_images = get_post_meta($post_id, 'myupload_images', true);
    foreach( (array)$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";
        }
    }
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<style>
  #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:180px; padding:4px; position:relative; background:#ccc; }
  #myupload_images li span img { margin:0; padding:0; height: auto; width:180px; 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 { width: 100%; padding:10px 15px; height:40px; line-height:20px; text-align:center; }
</style>

<div id="myupload_buttons">
  <a id="myupload_media" type="button" class="button" title="画像を追加・変更">画像の追加・削除</a>
  <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">
$(function(){
  var custom_uploader;
  $('#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() {
        // $('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 = $('#myupload_images'),
        ex_id = 0, 
        array_ids = [];
        if(ex_ul[0]) { //すでに登録されている画像を配列に格納
          ex_ul.children('li').each(function(){
            ex_id = Number($(this).attr('id').slice(4));
            array_ids.push(ex_id);
          });
        }
        console.log(images);
        images.each(function(file) {
          new_id = file.toJSON().id;
          if($.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();
    });
  $(document).on('click', '.myupload_images_remove', function( e ) {
    e.preventDefault();
    e.stopPropagation();
    img_obj = jQuery(this).parents('li.img').remove();
  });
  $('#myupload_images').sortable({
    axis : 'y',
    cursor : "move",
    tolerance : "pointer",
    opacity: 0.6
  });
});
</script>

<?php

}

/*------------------------------------------
 save
  ------------------------------------------*/
function save_myuploads_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 ); 
    }
  }
}
?>

URL出力はこんな感じでテンプレートファイルに。

<?php
$myupload_images = get_post_meta($post->ID, 'myupload_images', true);
if($myupload_images) : foreach($myupload_images as $img_id):
  $full_src = wp_get_attachment_image_src($img_id,'fullsize');
  if(!$full_src) continue;
  echo esc_html($full_src[0]);
endforeach; endif;
?>