Reputation: 1967
I want my users to be able to upload images to my website. They don't have to be logged in.
I have a custom Page template where I would like to perform this. And I have the following chunk of code inside my functions.php
wp_deregister_script('jquery');
wp_enqueue_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js', false, '1.11.3');
....
---------more codes are here---------
....
else if( in_category( $excluded, get_the_ID() ) || get_page_template_slug() == 'mediaCollector.php') {
wp_enqueue_media();
wp_enqueue_style('media_collector', get_stylesheet_directory_uri() . '/mediaCollector.css');
wp_enqueue_style('style_responsive', get_stylesheet_directory_uri() . '/style-responsive.css');
wp_enqueue_style('font-awesome', plugins_url() . '/my-plugin/css/font-awesome.min.css');
wp_enqueue_script('mediaCollectorScript', get_stylesheet_directory_uri() . '/mediaCollector.js');
}
....
---------more codes are here---------
....
This is the code for what happens when the Upload image button is clicked (which opens the popup where user can upload media).
\$j = jQuery.noConflict();
/* Logo Upload */
\$j(document).ready(function() {
\$j('.upload-btn').click(function(a) {
var that = this;
a.preventDefault();
var b = wp.media({
title: 'Upload Image',
multiple: !1
}).open().on('select', function(a) {
var c = b.state().get('selection').first();
var d = c.toJSON().url;
\$j(that).parent().find('input[type=text]').val(d)
});
});
But I am getting the following error on clicking the Upload button.
Uncaught TypeError: wp.media is not a function
Am I missing something? Any help is appreciated.
Upvotes: 5
Views: 13182
Reputation: 61
That solution has worked perfectly in my case
Add it in your functions.php
file of your active theme or in your plugin file.
function load_media_files() {
wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'load_media_files' );
Upvotes: 6
Reputation: 413
Try adding this
function load_media_files() {
wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'load_media_files' );
also if you get the reference is missing
in your javascript file, try this as well
wp_enqueue_script('mediaCollectorScript', get_stylesheet_directory_uri() . '/mediaCollector.js', array('jquery', 'media-upload'), '0.0.2', true);
Basically you have to add the third argument of wp_enqueue_script
function which is the dependencies for your javascript, which in this case, would be jquery
and media-upload
.
Upvotes: 19