Использование медиа библиотеки для кастомных полей WordPress

Небольшое руководство как добавить поддержку медиабиблиотеки для мета полей WordPress.

Весь код можно хранить в файле functions.php вашей темы.

add_action('add_meta_boxes', 'post_metabox_register');
function post_metabox_register()
{
   add_meta_box('battleMeta', __('Опции', 'default'), 'post_meta_box', 'post',
      'normal', 'low');
}

if (!function_exists('post_meta_box')) {
   function post_meta_box($post)
   {
        $_post_custom_image =get_post_meta($post->ID, '_post_custom_image', true);
      ?>

      <input type="hidden" name="_meta_update" value="1">
      <table>
            <tr>
                <td><label for="_post_custom_image">Дополнительная картинка</label></td>
                <td>
                    <input type="hidden" name="_post_custom_image" id="post_custom_image" value="<?php echo ($_post_custom_image) ? $_post_custom_image : ''; ?>">
                    <?php echo ($_post_custom_image) ? '<img src="'.$_post_custom_image.'">' : ''; ?>
                    <input id = "upload_image_button" type = "button" value = "Upload">
                </td>
            </tr>
      </table>
       <script type = "text/javascript">
            // Uploading files
            var file_frame;
            jQuery('#upload_image_button').live('click', function() {

                // If the media frame already exists, reopen it.
                if (file_frame) {
                    file_frame.open();
                    return;
                }
                // Create the media frame.
                file_frame = wp.media.frames.file_frame = wp.media({
                    title: jQuery(this).data('uploader_title'),
                    button: {
                        text: jQuery(this).data('uploader_button_text'),
                    },
                    multiple: false // Set to true to allow multiple files to be selected
                });

                // When a file is selected, run a callback.
                file_frame.on('select', function(){
                    // We set multiple to false so only get one image from the uploader
                    attachment = file_frame.state().get('selection').first().toJSON();
                    // here are some of the variables you could use for the attachment;
                    //var all = JSON.stringify( attachment );
                    //var id = attachment.id;
                    //var title = attachment.title;
                    //var filename = attachment.filename;
                    var url = attachment.url;
                    //var link = attachment.link;
                    //var alt = attachment.alt;
                    //var author = attachment.author;
                    //var description = attachment.description;
                    //var caption = attachment.caption;
                    //var name = attachment.name;
                    //var status = attachment.status;
                    //var uploadedTo = attachment.uploadedTo;
                    //var date = attachment.date;
                    //var modified = attachment.modified;
                    //var type = attachment.type;
                    //var subtype = attachment.subtype;
                    //var icon = attachment.icon;
                    //var dateFormatted = attachment.dateFormatted;
                    //var editLink = attachment.editLink;
                    //var fileLength = attachment.fileLength;
                    jQuery('#post_custom_image').val(url); //set which variable you want the field to have
                });

                // Finally, open the modal
                file_frame.open();
            });
        </script>
        <?php
   }
}

if (!function_exists('save_post_metabox')) {
   function save_post_metabox($post_ID, $post_type)
   {
      if (isset($_POST) && isset($_POST['_meta_update'])):
         $slug = 'post';

         if ($slug != $post_type->post_type) {
            return;
         }
            if (isset($_POST['_battle_team2_logo']))
                update_post_meta($post_ID, '_pust_custom_image', $_POST['_post_custom_image']);
            else
                update_post_meta($post_ID, '_post_custom_image', false);
      endif;
   }
}
add_action('save_post', 'save_post_metabox', 10, 2);

Таким образом, мы добавим дополнительное мета поле с возможностью прикрепить изображение из медиабиблиотеки.

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *