0

I am using the TinyMCE advanced editor for my Wordpress site. I want the users in the frontend to be able to upload images using the Wordpress media gallery, and for this purpose I would like to remap the Insert/edit image button, or add a new button (whichever is more feasible) to open the Wordpress media gallery, so that the Authors can add captions and alt text to their images:

enter image description here

I have been searching on the internet about this, but haven't found anything fruitful yet.

Can someone help in this regard?

1 Answer 1

1

The first thing you will need to do is be able to load up the WordPress media manager on the page you are using. This means you need to either load the core of WordPress or just call the media method from WP. The following code will load the WordPress core and que all of the files you need to be able to call the media manager.

require_once( 'wp-load.php' );
wp_enqueue_media();

The next thing to do is create a javascript function that will load up the WordPress media manager. The following function will do this and will then return the selected image to the instance of TinyMCE that triggered it. The reason for this, is you may have more than one instance of TinyMCE on the page and you want to make sure you return data to the correct one.

<script type="text/javascript">
function wpmediabrowser(field_name, url, type, win)
{
    var image = wp.media({ 
        title: 'Upload Image',
        multiple: false
    }).open().on('select', function(e){
    var uploaded_image = image.state().get('selection').first();
        jQuery("#" + field_name).val(uploaded_image["attributes"]["url"]);
        var arr = field_name.split('-');
        var field = arr[0];
        var number = parseInt(field.split('_')[1]) + 1;
        var descriptionid = field.split('_')[0] + "_" + number;
        jQuery("#" + descriptionid).val(uploaded_image["attributes"]["description"]);
    });
}
</script>

You can test if the function works by calling it using a href. The final step to do is to link this function in with the init of TinyMCE. The following code is all you need

"file_browser_callback: wpmediabrowser,";

This variable in the TinyMCE init will tell the app that you are using a file manager and to call a function called “wpmediabrowser” when the browse button is clicked. When you select the image from the WordPress file manager it will return the image url back into the box.

2
  • Thanks! But this is too complicated for me!
    – Sanu_012
    Jul 11, 2021 at 13:31
  • I figured it out using ACF and Elementor!
    – Sanu_012
    Jul 11, 2021 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.