Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- A function I use to quickly get a total of $limit-images (attachments), each from a unique parent post.
- Heavily used over at http://game.hgo.se/
- */
- function ulfben_get_post_images(
- $number_of_posts = 5,
- $category_filter = '66', //comma delimited list of category IDs
- $order_by = 'RAND()', //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 = (intval($number_of_posts) <= 0) ? 1 : $number_of_posts;
- $images = $wpdb->get_results(
- "SELECT SQL_SMALL_RESULT DISTINCT $wpdb->posts.post_parent, $wpdb->posts.ID
- FROM $wpdb->posts
- WHERE $wpdb->posts.post_parent IN (
- SELECT SQL_SMALL_RESULT DISTINCT $wpdb->posts.ID
- FROM $wpdb->posts
- LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
- LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
- WHERE $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN({$wpdb->escape($category_filter)})
- AND $wpdb->posts.post_type = 'post'
- AND $wpdb->posts.post_status = 'publish'
- AND $wpdb->posts.post_password = ''
- )
- AND $wpdb->posts.post_type = 'attachment'
- AND $wpdb->posts.post_mime_type IN ('image/jpeg', 'image/gif', 'image/png')
- ORDER BY {$order_by}
- LIMIT {$limit};"
- );
- $selection = array();
- foreach($images as $img){
- $imgurl = wp_get_attachment_image_src($img->ID, $size);
- if($imgurl === false){continue;} //the image doesn't exist?
- $img_width = $imgurl[1];
- $img_height = $imgurl[2];
- $imgurl = $imgurl[0];
- $selection[] = array(
- 'post_url' => get_permalink($img->post_parent),
- 'post_title' => wp_specialchars(get_the_title($img->post_parent)),
- 'post_id' => $img->post_parent,
- 'img_id' => $img->ID,
- 'img_src' => $imgurl,
- 'width' => $img_width,
- 'height' => $img_height
- );
- }
- 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='".esc_attr($image->post_title)."'><img src='{$image['img_src']}' alt='{$info}' {$image_attributes}/></a>";
- }
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement