WordPress的媒体按钮设置

时间:2018-06-21 13:00:54

标签: javascript jquery wordpress wordpress-theming

我在自己的wordpress管理员中建立了一个自定义选项页面。在其中,我有一些利用以下内容的“媒体”选择器按钮:

SPEECH//( STAGEDIR ;; LINE )

虽然效果很好,但我还没有发现如何将其限制为仅显示图像,而是显示整个媒体范围。

enter image description here

Current Screenshot

如何强制它仅使用/显示图像?

2 个答案:

答案 0 :(得分:1)

我的建议是更改查询参数,以便在媒体库中仅显示图像。您可以将以下代码段添加到您的functions.php文件中

add_filter('ajax_query_attachments_args', function($query){

  /**
   * check if you're on the correct page
   */
  if(filter_var($_SERVER['HTTP_REFERER'], FILTER_VALIDATE_URL) == 
     'https://yourhostdomain.com/wp-admin/admin.php?page=_your_options_page'){
      $query['post_mime_type'] = [
         'image/jpeg',
         'image/gif',
         'image/png',
         'image/bmp',
         'image/tiff',
         'image/x-icon'
      ];
  }
  return $query;
});

答案 1 :(得分:0)

我真的想通了。

我最终修改了问题中的代码,以包括“类型”检查以弹出完整的媒体浏览器,或仅弹出图像浏览器:

jQuery( document ).ready( function( $ ) {

    // pop the media box
    $('.gyo_upload').on( 'click', function( e ) {

        // prevent the default behavior
        e.preventDefault();

        // get what we're clicking
        var $button = $( this );

        // now figure out which one we want to popup
        var $what = $button.data( 'what' );

        // what do we actually want to popup here?
        if ( $what == 'image' ) {
            // image frame
            mediaUploader = wp.media.frames.file_frame = wp.media( {
                title: 'Choose Image',
                button: {
                text: 'Choose Image'
                }, multiple: false } );
            mediaUploader.on( 'select', function( ) {
                var $_which = $button.data( 'which' );
                var attachment = mediaUploader.state().get( 'selection' ).first().toJSON();
                $( '#img_' + $_which ).attr( 'src', attachment.url ).css( 'width', 'auto' );
                $( '#' + $_which ).val( attachment.url );
            } );
            mediaUploader.open();
        } else if ( $what == 'media' ) {
            // media frame
            var send_attachment_bkp = wp.media.editor.send.attachment;
            wp.media.editor.send.attachment = function( props, attachment ) {
                var $_which = $button.data( 'which' );
                $( '#img_' + $_which ).attr( 'src', attachment.url ).css( 'width', 'auto' );
                $( '#' + $_which ).val( attachment.url );
                wp.media.editor.send.attachment = send_attachment_bkp;
            }
            wp.media.editor.open( $button );
        }       

        return false;
    } );

    // process the remove attachment button
    $( '.remove_image_button' ).click( function() {
        var answer = confirm( 'Are you sure?' );
        if ( answer == true ) {
            var $this = $( this );
            var $_which = $this.data( 'which' );
            $( '#img_' + $_which ).attr('src', '');
            $( '#' + $_which ).val( '' );
        }
        return false;
    } );

} );