How to add image uploader to a custom widget?

I’v built a custom widget that will show some sport scores. Scores are added trough custom post. When i open new custom post(scores) i enter their team names, score, scores. Now i want to add an option to show team logos next to the team name. In the last couple of days every tutorial here and elsewhere i could find didnt worked. I have no idea why, as i am newbie with all this. With many of it, upload button appears but the pop up to chose/upload image doesnt appear. Now I could post at least 10 links where i found this codes but i believe there is a limit with link. So for an example this is most common tutorial i have found.

Here

The last one. Now in this case i am not sure about few things.

add_action('admin_enqueue_scripts', 'my_admin_scripts');

function my_admin_scripts() {
    if (isset($_GET['page']) && $_GET['page'] == 'my_plugin_page') {
        wp_enqueue_media();
        wp_register_script('my-admin-js', WP_PLUGIN_URL.'/my-plugin/my-admin.js', array('jquery'));
        wp_enqueue_script('my-admin-js');
    }
}

what exactly is this ‘my_plugin_page’ i guess i am doing something wrong and that’s why uploader doesnt pop up. What i need to add instead of it, any example?

Inside my theme i’v made a new folder called my-plugin inside which i added my-admin.js with the script code from the link above.

I also tried other way without it can calling the script by get_template_directory_uri().

Any help pls.

1 Answer
1

Firstly, it is not recommended to use WP_PLUGIN_URL constant, instead use plugins_url() function.

Second thing, it will not work when you put your files in the theme. You must put the necessary folder and file in the plugin if have to use this constant or function.

Make sure, you have put correct path and you JS file is being loaded properly.

wp_enque_media() is used to load necessary files and settings needed for a media uploader in the WP admin area. However, you should add necessary code specific to your uploader i.e. code for uploader on your custom post page.

The link that you have shown has covered enough code to implement WP media uploader in a plugin/theme.

Checking for my-plugin-page is not necessary. It’s added just to make sure that your script loaded only on necessary page and not all the pages. That too will be applicable when you have added an admin menu. In your case, I believe, you want the uploader on your custom post type edit page, so you can check for that instead.
Or for time being, just remove that condition, add necessary code in your my-admin.js and html in one of your plugin’s file as per tutorial given in the link shared by you.

Leave a Comment