Skip to content

Instantly share code, notes, and snippets.

@adamharley
Created August 23, 2011 16:36
Show Gist options
  • Save adamharley/1165780 to your computer and use it in GitHub Desktop.
Save adamharley/1165780 to your computer and use it in GitHub Desktop.
WP AJAX random image widget
jQuery(document).ready(function($) {
$.post(ajaxurl, {action:'random_image_widget'}, function(feedback){
image = jQuery.parseJSON(feedback);
img = $('<img src="'+image.thumb+'" />');
$('.widget_equesrandomimagewidget').append(img);
$(img).wrap('<a href="'+image.full[0]+'" width="'+image.full[1]+'" height="'+image.full[2]+'"></a>');
Shadowbox.setup(img.parent());
});
});
<?php
class RandomImageWidget extends WP_Widget {
function __construct() {
parent::WP_Widget( false, $name = 'Random Image Widget', array('description' => 'Displays a random image from the blog') );
if( ! is_admin() && is_active_widget(false, $this->id, $this->id_base) )
wp_enqueue_script('random-image-widget', plugin_dir_url(__FILE__).'random-image-widget.js', array('jquery'), null);
}
function register() {
return register_widget('RandomImageWidget');
}
function widget($args, $instance) {
extract($args);
$title = apply_filters('widget_title', $instance['title']);
echo $before_widget;
if ( $title )
echo $before_title . $title . $after_title;
echo '<div class="random-image-widget"></div>';
echo $after_widget;
}
function update($new_instance, $old_instance) {
return $new_instance;
}
function form($instance) {
$title = esc_attr($instance['title']);
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" /></label></p>
<?php
}
function ajax() {
global $wpdb;
$page_arr = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_type = 'page'" );
$pages = implode( ',', $page_arr );
$attachment_id = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment' AND post_mime_type = 'image/jpeg' AND post_parent NOT IN ($pages)" );
if ( ! $attachment_id )
die();
echo json_encode( array( 'full' => wp_get_attachment_url( $attachment_id ) ,'thumb' => wp_get_attachment_image_src( $attachment_id, array(215,500) ) ) );
die();
}
}
add_action( 'widgets_init', array('RandomImageWidget','register') );
add_action( 'wp_ajax_random_image_widget', array('RandomImageWidget','ajax') );
add_action( 'wp_ajax_nopriv_random_image_widget', array('RandomImageWidget','ajax') );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment