02 Jan Adding an Upload Field in Your Theme Options Panel
For anyone banging their heads against their keyboards trying to add upload functionality to their options panel, hopefully this can help.
All credit goes to Webmaster-Source.com’s article, you can read here.
I just wanted to try to make it a little more clear and show you the bits and pieces of code that I am using.
Step 1. Register your setting in your functions.php:
1 2 3 4 5 | register_setting( 'themeOptions', 'logoUpload' ); /* Remember, the first parameter [themeOptions] is the group option name and the second parameter [logoUpload] is the option name. You can rename them to anything you want. */ |
Step 2. Also, make sure you add it inside your form:
1 2 3 4 | settings_fields( 'themeOptions', 'logoUpload' ); /* If you forget to add this inside your form, when you go to save your data, you will get a 'options.php not found' */ |
Step3. Getting your HTML ready in Your Form:
1 2 | <input id="logoUpload" type="text" size="55" name="logoUpload" value="<?php echo get_option('logoUpload');?>" /> //Set the input with the id="logoUpload" so jQuery can find it. |
Step 4. Calling the Scripts:
You need to call the appropriate scripts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // <-- Check to see if you are on the right page if (isset($_GET['page']) && $_GET['page'] == 'theme_options') { add_action('admin_print_scripts', 'admin_scripts'); add_action('admin_print_styles', 'admin_styles'); } function admin_scripts() { //We register our custom jQuery script, which you can see in step 6... wp_register_script('logoUpload',BASE.'/options/logoUpload.js', array('jquery','media-upload','thickbox')); //..then we call it wp_enqueue_script('logoUpload'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); } function admin_styles() { wp_enqueue_style('thickbox'); } |
Step 5. Finding last post->ID:
To be able to see the ‘insert into post’ button, WordPress needs a post->ID. Put this in your options panel function, so we can call it in your jQuery script[step 6]
1 2 | global $post; $lastPost = get_posts('order=ASC&numberposts=1'); |
Step 6. The jQuery Script -> uploadLogo.js
Here is how your jQuery should look. Basically it looks for the element #logoUpload, which we set on the input field in our form. Then it plugs the post->ID into the thickbox URL.
1 2 3 4 5 6 7 8 9 10 11 12 13 | jQuery('#logoUpload').click(function () { formfield = jQuery('#logoUpload'); post_id = jQuery('post_id=$lastPost[0]->ID').val(); window.send_to_editor = window.send_to_editor_clone; tb_show('', 'media-upload.php?post_id=' + post_id + '&type=image&TB_iframe=true'); return false; }); window.send_to_editor_clone = function (html) { imgurl = jQuery('img', html).attr('src'); jQuery('#logoUpload').val(imgurl); tb_remove(); } }); |
Sorry, the comment form is closed at this time.