2017-02-20 23 views
1

Я создаю медиа-загрузчик галереи в мета-поле. Он отлично работает.Как получить шорткод галереи wp при создании галереи в мета-поле

enter image description here

Когда я нажимаю на Browse, грузчик галереи СМИ вверх открыт, я выбираю изображения, а затем нажмите на Insert Gallery, но я не получил шорткод из галереи во входном мете поля.

Вот мой код, который я получаю из интернета:

var meta_image_frame_gallery; 
    $('#additional_image_1').click(function(event) { 
     event.preventDefault(); 

     //var images = $('#itv_additional_image_1').val(); 
     //var gallery_state = images ? 'gallery-edit' : 'gallery-library'; 

     if (meta_image_frame_gallery) { 
      meta_image_frame_gallery.open(); 
      return; 
     } 

     // create new media frame 
     // You have to create new frame every time to control the Library state as well as selected images 
     meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media({ 
      title: 'My Gallery', // it has no effect but I really want to change the title 
      frame: "post", 
      //toolbar: 'main-gallery', 
      state: 'gallery-library', 
      library: { 
       type: 'image' 
      }, 
      multiple: true 
     }); 

    }); 

А вот мой HTML код:

<input id="itv_additional_image_1" class="input-text" name="itv_additional_image_1" placeholder="" type="text"> 
<input id="additional_image_1" name="additional_image_1" value="Browse" type="button"> 

Я очень слаб в JQuery, поэтому, пожалуйста, руководство меня по этому вопросу

+0

** но я не получил короткий код галереи во входном метаполе **. Что вы точно имеете в виду? Не могли бы вы рассказать о своем вопросе? –

+0

Можете ли вы быть более ясными? что вы подразумеваете под «но я не получил короткий код галереи во входном мета-поле». В чем проблема? –

+0

@deemi вы можете проверить мой ответ –

ответ

2

Можете ли вы попробовать ниже код:

JQuery:

$(document).ready(function(){ 
    var meta_image_frame_gallery; 
    $('#additional_image_1').click(function(event) { 
     event.preventDefault(); 

     if (meta_image_frame_gallery) { 
      meta_image_frame_gallery.open(); 
      return; 
     } 

     // create new media frame 
     // You have to create new frame every time to control the Library state as well as selected images 
     meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media({ 
      title: 'My Gallery', // it has no effect but I really want to change the title 
      frame: "post", 
      //toolbar: 'main-gallery', 
      state: 'gallery-library', 
      library: { 
       type: 'image' 
      }, 
      multiple: true, 
     }); 

     /* Add image gallery shortcode in itv_additional_image_1 input filed when close event call */ 
     meta_image_frame_gallery.on('close',function() { 
      //fetch the gallery state 
      var controller = meta_image_frame_gallery.states.get('gallery-library'); 
      var library = controller.get('library'); 
      //get the shortcode and update the input field 
      var new_shortcode = wp.media.gallery.shortcode(library).string(); 
      $('#itv_additional_image_1').val(new_shortcode); 
     }); 

     /* Update event for image gallery */ 
     meta_image_frame_gallery.on('update', function() { 
      var controller = meta_image_frame_gallery.states.get('gallery-edit'); 
      var library = controller.get('library'); 
      var new_shortcode = wp.media.gallery.shortcode(library).string(); // Get the new/updated shortcode here. 
      $('#itv_additional_image_1').val(new_shortcode); 
     }); 
    }); 
}); 

код проверяется в работе идеально. элемент галереи обновления также отлично работает.

+0

thanx alot dear ... вы действительно спасите мой день ... thanx again bro – deemi

+0

вы там ... мне нужна помощь по этой теме – deemi

+0

Да, я здесь ... –

2

вам нужно

  • добавьте событие «закрыть» для кадра wp.media
  • введите код короткого замыкания из wp.media внутри события закрытия и передайте его на вход
  • Добавить save_action hook на wordpress, чтобы сохранить это значение, когда сообщение сохраняется/опубликовано
  • Кроме того, вам может потребоваться извлечь текущие элементы галереи из ввода и передать их в фрейм wp.media, чтобы можно было использовать ранее выбранное изображение.

Вы можете использовать следующий рабочий код и протестировать свою установку WordPress.

//add action for the custom gallery 
add_action("add_meta_boxes", "add_custom_meta_box_gallery"); 
function add_custom_meta_box_gallery() 
{ 
    add_meta_box("demo-meta-box", "Custom Meta Box", "custom_meta_box_gallery_markup", "post"); 
} 

function custom_meta_box_gallery_markup($object) 
{ 
    wp_nonce_field(basename(__FILE__), "meta-box-nonce"); 
    ?> 
    <div> 
     <label for="meta-box-text">Gallery</label> 
     <!-- avoid double quote for with value as shortcode string also has doulbe qoutes. so instead of value="..." use value='....' --> 
     <input value='<?php echo get_post_meta($object->ID, "meta-box-gallery", true); ?>' id="itv_additional_image_1" class="input-text" name="meta-box-gallery" placeholder="" type="text"> 
     <input id="additional_image_1" name="additional_image_1" value="Browse" type="button"> 
<script> 
    //utility function to convert the string shortcode to wp.media selection 
    function select(shortcode) { 
     var shortcode = wp.shortcode.next('gallery', shortcode); 
     var defaultPostId = wp.media.gallery.defaults.id; 
     var attachments; 
     var selection; 

     // Bail if we didn't match the shortcode or all of the content. 
     if (!shortcode) { 
      return; 
     } 

     shortcode = shortcode.shortcode; 

     if (typeof shortcode.get('id') != 'undefined' && typeof defaultPostId != 'undefined') { 
      shortcode.set('id', defaultPostId); 
     } 

     attachments = wp.media.gallery.attachments(shortcode); 
     selection = new wp.media.model.Selection(attachments.models, { 
      props : attachments.props.toJSON(), 
      multiple: true 
     }); 

     selection.gallery = attachments.gallery; 

     /* 
     * Fetch the query's attachments, and then break ties from the query to allow for sorting. 
     */ 
     selection.more().done(function() { 
      // Break ties with the query. 
      selection.props.set({ 
       query: false 
      }); 
      selection.unmirror(); 
      selection.props.unset('orderby'); 
     }); 
     return selection; 
    } 
//better to use javascript-self-invoking-functions to avoid variable leaks 
    (function($){ 
     var meta_image_frame_gallery; 
     $('#additional_image_1').click(function(event) { 
      console.log('d') 
      event.preventDefault(); 

      //var images = $('#itv_additional_image_1').val(); 
      //var gallery_state = images ? 'gallery-edit' : 'gallery-library'; 

      if (meta_image_frame_gallery) { 
       meta_image_frame_gallery.open(); 
       return; 
      } 

      //get the current gallery items 
      var currentItems = select($('#itv_additional_image_1').val()); 
      // create new media frame 
      // You have to create new frame every time to control the Library state as well as selected images 
      meta_image_frame_gallery = wp.media.frames.wp_media_frame = wp.media({ 
       title: 'My Gallery', // it has no effect but I really want to change the title 
       frame: "post", 
       //toolbar: 'main-gallery', 
       state: 'gallery-library', 
       selection: currentItems, 
       library: { 
        type: 'image' 
       }, 
       multiple: true 
      }); 

      //add close event to the frame 
      meta_image_frame_gallery.on('close',function() { 
       //fetch the gallery state 
       var controller = meta_image_frame_gallery.states.get('gallery-library'); 
       var library = controller.get('library'); 
       //get the shortcode and update the input field 
       var new_shortcode = wp.media.gallery.shortcode(library).string(); 
       $('#itv_additional_image_1').val(new_shortcode); 
      }); 

      //open the wp.media frame 
      meta_image_frame_gallery.open(); 

     }); 
    })(jQuery); 

</script> 
    </div> 
    <?php 
} 

//save the value 
function save_custom_meta_box_gallery($post_id, $post, $update) 
{ 
    if (!isset($_POST["meta-box-nonce"]) || !wp_verify_nonce($_POST["meta-box-nonce"], basename(__FILE__))) 
     return $post_id; 

    if(!current_user_can("edit_post", $post_id)) 
     return $post_id; 

    if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) 
     return $post_id; 

    $slug = "post"; 
    if($slug != $post->post_type) 
     return $post_id; 

    $meta_box_text_value = ""; 

    if(isset($_POST["meta-box-gallery"])) 
    { 
     $meta_box_text_value = $_POST["meta-box-gallery"]; 
    } 
    update_post_meta($post_id, "meta-box-gallery", $meta_box_text_value); 
} 

add_action("save_post", "save_custom_meta_box_gallery", 10, 3); 

Если вы это подавляющий вы можете попробовать ACF Gallery module из ACF plugin