Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- These functions are great for WordPress sites with posts and media that have been imported. Some images are featured images, some in the content itself, and of the content images, some are internal, others external. These images are grabbed to use at the correct size for archive/homepage thumbnails*/
- 1) Look for featured image, show if present
- 2) Otherwise look for the first image in the content (whether internal or external)
- 3) Check for an attachment ID, if present, show image at correct dimensions
- 4) Otherwise show image at normal URL
- $size = post thumbnail / custom image sizes
- $url = return a URL or full image tag
- */
- /*Find the image id from a URL*/
- function url_get_image_id($image_url) {
- global $wpdb;
- $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
- return $attachment[0];
- }
- /* determine whether post has a featured image, if not, find the first image inside the post content, $size passes the thumbnail size, $url determines whether to return a URL or a full image tag*/
- function checkImageType($size, $type) {
- global $post;
- $content = $post->post_content;
- $first_img = '';
- ob_start();
- ob_end_clean();
- $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches);
- $first_img = $matches[1][0];
- /*If there's a featured image, show it*/
- if (get_the_post_thumbnail($post_id) != '' ) {
- if($type=='url') {
- the_post_thumbnail_url($size);
- } else {
- the_post_thumbnail($size);
- }
- } else {
- /*No featured image, so we get the first image inside the post content*/
- if ($first_img) {
- //let's get the correct image dimensions
- $image_id = url_get_image_id($first_img);
- $image_thumb = wp_get_attachment_image_src($image_id, $size);
- // if we've found an image ID, correctly display it
- if($image_thumb) {
- if($type=='url') {
- echo $image_thumb[0];
- } else {
- echo '<img src="'.$image_thumb[0].'" alt="'.get_the_title().'"/>';
- }
- } else {
- //if no image (i.e. from an external source), echo the original URL
- if($type=='url') {
- echo $first_img;
- } else {
- echo '<img src="'.$first_img.'" alt="'.get_the_title().'"/>';
- }
- }
- }
- }
- }
- // Sample Uses
- checkImageType('full', 'url');
- // Returns: http://domain.com/image-url.jpg)
- checkImageType('post-thumb');
- // Returns: <img src="http://domain.com/image-url.jpg" alt="Alt text">
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement