Develop with the new WordPress 3.5 Media Manager.

Overview

If you are a WordPress plugin developer, you may want to use the new build-in WordPress 3.5 Media Manager in your plugin. This tutorial will teach you how to implement the Media-Manager in your plugin.

Download

Download From Git

I’ve forked from ThomasGriffin on GItHub. he created wonderful example of integrating the new Media Manager into MetaBox. based on his work, i’ve added the plugin implementation of the Media Manager.

You can git clone the project from my GitHub: https://github.com/ET-CS/WP3.5-Media-Manager-Demo.git

git clone https://github.com/ET-CS/WP3.5-Media-Manager-Demo.git.

if you not sure how to work with git, you can visit my articles:

If you don’t use Git or don’t want to, you can always copy the files directly from GitHub. there are only 4 of them.

 

Download ZIP

Download the demo from Git (above) or download the .ZIP file from our WordPress plugins page.

 

Try the demo

After you’ve downloaded either from Git or .Zip File:

  1. add the plugin to your WordPress setup, either by unzip the zip file to the /wp-content/plugins directory, or by Git Clone inside this folder.
  2. Activate the plugin

You can see two changes:

  1. New settings page called ‘Media Manager Demo‘ inside your wp-admin settings page.
  2. New Meta Box below the TinyMCE editor in your Pages.

Both are practically the same, demo button and textbox, lets you choose or upload file using the WP 3.5 New Media Manager and then show the file name inside the textbox.

 

Under the hood

How it is work? how to implement it in your plugin?

While you should explore the simple code, three parts are the most important for this to work:

  1. function assets() in file new-media-plugin.php:
    this function loads the scripts required for the implementation to work. including media.js bundled with the plugin. note the first part of the function, bail out early if the screen is not a page or settings page. you should adjust it for your needs.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    public function assets() {
     
            // name of settings page
            $settings = 'settings_page_'.NEW_NEDIA_PLUGIN_MENU_SLUG;
            // Bail out early if we are not on a page add/edit screen.
            // First part (before &&) is checks if it is a page. second part to check if this is the settings page.
            if ( ( ! ( 'post' == get_current_screen()->base && 'page' == get_current_screen()->id ) ) && ( ! ( $settings == get_current_screen()->base && $settings == get_current_screen()->id ) ) )
                return;
     
            // This function loads in the required media files for the media manager.
            wp_enqueue_media();
     
            // Register, localize and enqueue our custom JS.
            wp_register_script( 'nmp-media', plugins_url( '/js/media.js', __FILE__ ), array( 'jquery' ), '1.0.0', true );
            wp_localize_script( 'nmp-media', 'nmp_media',
                array(
                    'title'     => __( 'Upload or Choose Your Custom Image File', 'nmp' ), // This will be used as the default title
                    'button'    => __( 'Insert Image into Input Field', 'nmp' )            // This will be used as the default button text
                )
            );
            wp_enqueue_script( 'nmp-media' );
     
        }
    public function assets() {
    
    		// name of settings page
    		$settings = 'settings_page_'.NEW_NEDIA_PLUGIN_MENU_SLUG;
    		// Bail out early if we are not on a page add/edit screen.
    		// First part (before &&) is checks if it is a page. second part to check if this is the settings page.
            if ( ( ! ( 'post' == get_current_screen()->base && 'page' == get_current_screen()->id ) ) && ( ! ( $settings == get_current_screen()->base && $settings == get_current_screen()->id ) ) )
                return;
    
            // This function loads in the required media files for the media manager.
            wp_enqueue_media();
    
            // Register, localize and enqueue our custom JS.
            wp_register_script( 'nmp-media', plugins_url( '/js/media.js', __FILE__ ), array( 'jquery' ), '1.0.0', true );
            wp_localize_script( 'nmp-media', 'nmp_media',
                array(
                    'title'     => __( 'Upload or Choose Your Custom Image File', 'nmp' ), // This will be used as the default title
                    'button'    => __( 'Insert Image into Input Field', 'nmp' )            // This will be used as the default button text
                )
            );
            wp_enqueue_script( 'nmp-media' );
    
        }
  2. add_meta_box() & create_admin_menu():
    each handles creating of Meta box and Admin settings page relatively.
    They also render the necessary HTML code to generate the button:
    [code lang=”php” inline=”yes”]echo ‘<div id=”new-media-settings”>’;
    echo ‘<p>’ . __( ‘Click on the button below to open up the media modal and watch your customizations come to life!’, ‘nmp’ ) . ‘</p>’;
    echo ‘<p><strong>’ . __( ‘Please note that none of this will save when you update the page. This is just for demonstration purposes only!’, ‘nmp’ ) . ‘</strong></p>’;
    echo ‘<p><a href=”#” class=”open-media button button-primary” title=”‘ . esc_attr__( ‘Click Here to Open the Media Manager’, ‘nmp’ ) . ‘”>’ . __( ‘Click Here to Open the Media Manager’, ‘nmp’ ) . ‘</a></p>’;
    echo ‘<p><label for=”new-media-image”>’ . __( ‘Our Image Goes Here!’, ‘nmp’ ) . ‘</label> <input type=”text” id=”new-media-image” size=”70″ value=”” /></p>’;
    echo ‘</div>’;[/code]
  3. the file media.js inside /js folder. required for the media gallery to show. you can adjust settings there if you decided to change the HTML code.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    
    /**
     * Main jQuery media file for the plugin.
     *
     * @since 1.0.0
     *
     * @package New Media Plugin
     * @author  Thomas Griffin
     */
    jQuery(document).ready(function($){
        // Prepare the variable that holds our custom media manager.
        var media_frame;
     
        // Bind to our click event in order to open up the new media experience.
        $(document.body).on('click.OpenMediaManager', '.open-media', function(e){
            // Prevent the default action from occuring.
            e.preventDefault();
     
            // If the frame already exists, re-open it.
            if ( media_frame ) {
                media_frame.open();
                return;
            }
     
            /**
             * The media frame doesn't exist let, so let's create it with some options.
             *
             * This options list is not exhaustive, so I encourage you to view the
             * wp-includes/js/media-views.js file to see some of the other default
             * options that can be utilized when creating your own custom media workflow.
             */
            media_frame = wp.media.frames.media_frame = wp.media({
                /**
                 * We can pass in a custom class name to our frame, so we do
                 * it here to provide some extra context for styling our
                 * media workflow. This helps us to prevent overwriting styles
                 * for other media workflows.
                 */
                className: 'media-frame media-frame',
     
                /**
                 * When creating a new media workflow, we are given two types
                 * of frame workflows to chose from: 'select' or 'post'.
                 *
                 * The 'select' workflow is the default workflow, mainly beneficial
                 * for uses outside of a post or post type experience where a post ID
                 * is crucial.
                 *
                 * The 'post' workflow is tailored to screens where utilizing the
                 * current post ID is critical.
                 *
                 * Since we only want to upload an image, let's go with the 'select'
                 * frame option.
                 */
                frame: 'select',
     
                /**
                 * We can determine whether or not we want to allow users to be able
                 * to upload multiple files at one time by setting this parameter to
                 * true or false. It defaults to true, but we only want the user to
                 * upload one file, so let's set it to false.
                 */
                multiple: false,
     
                /**
                 * We can set a custom title for our media workflow. I've localized
                 * the script with the object 'nmp_media' that holds our
                 * localized stuff and such. Let's populate the title with our custom
                 * text.
                 */
                title: nmp_media.title,
     
                /**
                 * We can force what type of media to show when the user views his/her
                 * library. Since we are uploading an image, let's limit the view to
                 * images only.
                 */
                library: {
                    type: 'image'
                },
     
                /**
                 * Let's customize the button text. It defaults to 'Select', but we
                 * can customize it here to give us better context.
                 *
                 * We can also determine whether or not the modal requires a selection
                 * before the button is enabled. It requires a selection by default,
                 * and since this is the experience desired, let's keep it that way.
                 *
                 * By default, the toolbar generated by this frame fires a generic
                 * 'select' event when the button is clicked. We could declare our
                 * own events here, but the default event will work just fine.
                 */
                button: {
                    text:  nmp_media.button
                }
            });
     
            /**
             * ========================================================================
             * EVENT BINDING
             *
             * This section before opening the modal window should be used to bind to
             * any events where we want to customize the view. This includes binding
             * to any custom events that may have been generated by us creating
             * custom controller states and views.
             *
             * The events used below are not exhaustive, so I encourage you to again
             * study the wp-includes/js/media-views.js file for a better feel of all
             * the potential events you can attach to.
             * ========================================================================
             */
     
            /**
             * We are now attaching to the default 'select' event and grabbing our
             * selection data. Since the button requires a selection, we know that a
             * selection will be available when the event is fired.
             *
             * All we are doing is grabbing the current state of the frame (which will
             * be 'library' since that's the only area where we can make a selection),
             * getting the selection, calling the 'first' method to pluck the first
             * object from the string and then forcing a faux JSON representation of
             * the model.
             *
             * When all is said and done, we are given absolutely everything we need to
             * insert the data into our custom input field. Specifically, our
             * media_attachment object will hold a key titled 'url' that we want to use.
             */
            media_frame.on('select', function(){
                // Grab our attachment selection and construct a JSON representation of the model.
                var media_attachment = media_frame.state().get('selection').first().toJSON();
     
                // Send the attachment URL to our custom input field via jQuery.
                $('#new-media-image').val(media_attachment.url);
            });
     
            // Now that everything has been set, let's open up the frame.
            media_frame.open();
        });
    });
    /**
     * Main jQuery media file for the plugin.
     *
     * @since 1.0.0
     *
     * @package New Media Plugin
     * @author  Thomas Griffin
     */
    jQuery(document).ready(function($){
        // Prepare the variable that holds our custom media manager.
        var media_frame;
    
        // Bind to our click event in order to open up the new media experience.
        $(document.body).on('click.OpenMediaManager', '.open-media', function(e){
            // Prevent the default action from occuring.
            e.preventDefault();
    
            // If the frame already exists, re-open it.
            if ( media_frame ) {
                media_frame.open();
                return;
            }
    
            /**
             * The media frame doesn't exist let, so let's create it with some options.
             *
             * This options list is not exhaustive, so I encourage you to view the
             * wp-includes/js/media-views.js file to see some of the other default
             * options that can be utilized when creating your own custom media workflow.
             */
            media_frame = wp.media.frames.media_frame = wp.media({
                /**
                 * We can pass in a custom class name to our frame, so we do
                 * it here to provide some extra context for styling our
                 * media workflow. This helps us to prevent overwriting styles
                 * for other media workflows.
                 */
                className: 'media-frame media-frame',
    
                /**
                 * When creating a new media workflow, we are given two types
                 * of frame workflows to chose from: 'select' or 'post'.
                 *
                 * The 'select' workflow is the default workflow, mainly beneficial
                 * for uses outside of a post or post type experience where a post ID
                 * is crucial.
                 *
                 * The 'post' workflow is tailored to screens where utilizing the
                 * current post ID is critical.
                 *
                 * Since we only want to upload an image, let's go with the 'select'
                 * frame option.
                 */
                frame: 'select',
    
                /**
                 * We can determine whether or not we want to allow users to be able
                 * to upload multiple files at one time by setting this parameter to
                 * true or false. It defaults to true, but we only want the user to
                 * upload one file, so let's set it to false.
                 */
                multiple: false,
    
                /**
                 * We can set a custom title for our media workflow. I've localized
                 * the script with the object 'nmp_media' that holds our
                 * localized stuff and such. Let's populate the title with our custom
                 * text.
                 */
                title: nmp_media.title,
    
                /**
                 * We can force what type of media to show when the user views his/her
                 * library. Since we are uploading an image, let's limit the view to
                 * images only.
                 */
                library: {
                    type: 'image'
                },
    
                /**
                 * Let's customize the button text. It defaults to 'Select', but we
                 * can customize it here to give us better context.
                 *
                 * We can also determine whether or not the modal requires a selection
                 * before the button is enabled. It requires a selection by default,
                 * and since this is the experience desired, let's keep it that way.
                 *
                 * By default, the toolbar generated by this frame fires a generic
                 * 'select' event when the button is clicked. We could declare our
                 * own events here, but the default event will work just fine.
                 */
                button: {
                    text:  nmp_media.button
                }
            });
    
            /**
             * ========================================================================
             * EVENT BINDING
             *
             * This section before opening the modal window should be used to bind to
             * any events where we want to customize the view. This includes binding
             * to any custom events that may have been generated by us creating
             * custom controller states and views.
             *
             * The events used below are not exhaustive, so I encourage you to again
             * study the wp-includes/js/media-views.js file for a better feel of all
             * the potential events you can attach to.
             * ========================================================================
             */
    
            /**
             * We are now attaching to the default 'select' event and grabbing our
             * selection data. Since the button requires a selection, we know that a
             * selection will be available when the event is fired.
             *
             * All we are doing is grabbing the current state of the frame (which will
             * be 'library' since that's the only area where we can make a selection),
             * getting the selection, calling the 'first' method to pluck the first
             * object from the string and then forcing a faux JSON representation of
             * the model.
             *
             * When all is said and done, we are given absolutely everything we need to
             * insert the data into our custom input field. Specifically, our
             * media_attachment object will hold a key titled 'url' that we want to use.
             */
            media_frame.on('select', function(){
                // Grab our attachment selection and construct a JSON representation of the model.
                var media_attachment = media_frame.state().get('selection').first().toJSON();
    
                // Send the attachment URL to our custom input field via jQuery.
                $('#new-media-image').val(media_attachment.url);
            });
    
            // Now that everything has been set, let's open up the frame.
            media_frame.open();
        });
    });

HTML, combined with the media.js gives you the media manager implementation you’ve needed!

 

Happy implementing!

5 thoughts on “Develop with the new WordPress 3.5 Media Manager.

  1. http://www.onlinekredit.tech/

    Gini lah…kekawan semua. kawe rase lebih kita berzikir drpd ambil tau kisah si haprak ni.Lagipun JAIP memang akan lepaskan dia. Cable bapok dinasor tu. Kalau tak pecaya, dema tunggu jer…lah endingnya.ha ha ha.. aku dah malas nak percaya org2 kat pej.agama ni..buat penat bagi info jer.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.