I want to create a custom widget so the user can select 2 images from the media library via a dropdown box and display them in a sidebar.
So I need the widget to display 2 drop downs, which each show the TITLE of the images in the media library.
I then need to save the url of these two images to use in the front-end (labelled <?php $IMAGEVAR ?>
in the widget
function.
Here is my widget template ->
<?php
class Image_Picker extends WP_Widget
{
function Image_Picker() {
$widget_ops = array('classname' => 'Image_Picker', 'description' => 'Pick 2 images from media library');
$this->WP_Widget('Image_Picker', 'Image Picker', $widget_ops);
}
function form() {
//WIDGET BACK-END SETTINGS
echo '<select name="link1">';
echo '<option value="image1" selected>Image 1 Title</option>';
echo '<option value="image2">Image 2 Title</option>';
echo '<option value="image3">Image 3 Title</option>';
echo '</select><br>';
echo '<select name="link2">';
echo '<option value="image1" selected>Image 1 Title</option>';
echo '<option value="image2">Image 2 Title</option>';
echo '<option value="image3">Image 3 Title</option>';
echo '</select>';
}
function update() {
//WIDGET SAVE FUNCTION
}
function widget() {
//WIDGET FRONT-END VIEW
?>
<!-- Display images -->
<div class="sidebar-image"><img src="<?php $IMAGEVAR ?>" alt="" width="203" height="271" border="0"></div>
<div class="sidebar-image"><img src="<?php $IMAGEVAR ?>" alt="" width="177" height="207" border="0"></div>
<?php
}
}
// Add class for Random Posts Widget
add_action( 'widgets_init', create_function('', 'return register_widget("Image_Picker");') );
?>
I have been doing this as a meta box for posts, but I need to make a widget version and can’t work out how to implement it. I have added in a front-end template to illustrate how it works as a widget, this template will show as a widget if you include it in your functions.php
, but obviously it won’t do anything…
Any help is greatly appreciated, cheers.
Try this code.