Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*refactored version of http://pastebin.com/f5cdfcd4c */
- /*returns one image per (published & public) post.
- use params to control the number of posts, the categories, the sort order and image size.
- @returns array(array('post_url', 'post_title','post_id','img_src'), [...])*/
- function ulfben_get_post_images($number_of_posts = 5,
- $category_filter = '66', //comma delimited list of category IDs
- $order_by = 'RAND()', //{$wpdb->posts}.post_date DESC or what have you.
- $size = 'thumbnail'){//'thumbnail', 'medium', 'large' or 'full' or an array of width and height, e.g. array(32,32)
- global $wpdb;
- $limit = (is_int($number_of_posts) && $number_of_posts > 0) ? $number_of_posts : 1; //select 1 if the parameter seems stupid.
- $query="SELECT {$wpdb->posts}.post_parent, {$wpdb->posts}.ID
- FROM {$wpdb->posts}
- INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.post_parent = {$wpdb->term_relationships}.object_id)
- INNER JOIN {$wpdb->term_taxonomy} ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)
- WHERE {$wpdb->posts}.post_type = 'attachment'
- AND {$wpdb->term_taxonomy}.taxonomy = 'category' AND {$wpdb->term_taxonomy}.term_id IN ('{$wpdb->escape($category_filter)}')
- AND {$wpdb->posts}.post_password = ''
- AND {$wpdb->posts}.post_mime_type IN ('image/jpeg', 'image/gif', 'image/png')
- GROUP BY {$wpdb->posts}.post_parent
- ORDER BY {$order_by}
- LIMIT {$limit};";
- $results = $wpdb->get_results($query);
- $selection = array();
- foreach($results as $result){
- $parent_post_id = $result->post_parent;
- $image_id = $result->ID;
- $imgurl = wp_get_attachment_image_src($image_id, $size);
- if($imgurl === false){continue;} //the image doesn't exist in the requested size!
- $imgurl = $imgurl[0];
- $post_url = get_permalink( $parent_post_id );
- $post_title = $wpdb->get_var("SELECT {$wpdb->posts}.post_title
- FROM {$wpdb->posts}
- WHERE {$wpdb->posts}.ID = {$parent_post_id}
- LIMIT 1;"
- );
- $selection[] = array('post_url'=>$post_url, 'post_title' => wp_specialchars($post_title),'post_id'=>$parent_post_id, 'img_src'=>$imgurl);
- }
- return $selection;
- }
- function ulfben_print_post_images($number_of_posts = 5, //number of posts
- $image_attributes = '',
- $category_filter = '66', //comma delimited list of category IDs
- $order_by = 'RAND()', //{$wpdb->posts}.post_date DESC or what have you.
- $size = 'thumbnail'){//'thumbnail', 'medium', 'large' or 'full' or an array of width and height, e.g. array(32,32)
- $images = ulfben_get_post_images($number_of_posts, $category_filter, $order_by, $size);
- foreach($images as $image){
- echo "<a href='{$image['post_url']}' title='{$image['post_title']}'><img src='{$image['img_src']}' alt='{$image['post_title']}' {$image_attributes}/></a>";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement