简体   繁体   English

WordPress-将第一个图像设置为旧帖子的特色图像

[英]Wordpress - Setting First Image as Featured Image for Older Posts

I am using the following code to pull the first image from a blog post as a 'featured image': 我正在使用以下代码从博客文章中提取第一张图片作为“精选图片”:

function auto_featured_image() {
    global $post;

    if (!has_post_thumbnail($post->ID)) {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );

      if ($attached_image) {
              foreach ($attached_image as $attachment_id => $attachment) {
                   set_post_thumbnail($post->ID, $attachment_id);
              }
         }
    }
}
// Use it temporary to generate all featured images
add_action('the_post', 'auto_featured_image');
// Used for new posts
add_action('save_post', 'auto_featured_image');
add_action('draft_to_publish', 'auto_featured_image');
add_action('new_to_publish', 'auto_featured_image');
add_action('pending_to_publish', 'auto_featured_image');
add_action('future_to_publish', 'auto_featured_image');

It works well for recent blog posts, but older posts it can't seem to pull. 它对于最近的博客文章效果很好,但是较旧的文章似乎无法撤消。 I suspect the theme template back then was perhaps doing something different? 我怀疑当时的主题模板可能在做一些不同的事情? We are trying to prevent having to set 200+ featured images manually and would love to get this working. 我们正在尝试避免手动设置200幅以上的特色图像,并希望能够正常运行。

When I look at the source code for the images that are pulled, it shows as the following: 当我查看被拉取的图像的源代码时,它显示如下:

<div class="entry-image relative">
                <a href="https://mywebsite.com/2017/08/getting-out/">
    <img src="https://mywebsite.com/wp-content/uploads/2017/08/BoiseTrip2017_0129.jpg" class="attachment-large size-large wp-post-image" alt="" width="1020" height="635"></a>

However for those that aren't being pulled, it shows as the following: 但是,对于未拉出的那些,它显示如下:

<div class="entry-content single-page">

    <p><a href="http://www.mywebsite.com/wp-content/uploads/2017/09/leather-briefcase-bag-mens-shoulder-bag_243_0036.jpg"><img class="aligncenter size-full wp-image-57946" src="http://www.mywebsite.com/wp-content/uploads/2017/09/leather-briefcase-bag-mens-shoulder-bag_243_0036.jpg" alt="mens leather briefcase" width="1100" height="733"></a></p>

To me, this suggests it perhaps had another template. 对我来说,这表明它可能还有另一个模板。 It also could be that the image is embedded in a 'p' tag. 图像也可能嵌入在“ p”标签中。 I tried going back to that post and making sure this is no < p > anywhere around the image in the original post and there is not. 我尝试返回该帖子,并确保在原始帖子中图像周围的任何地方都没有<p>,并且没有。

Ok, this is going to look like a huge data dump because, frankly, that's what it is. 好的,这看起来像是一个巨大的数据转储,因为坦率地说就是这样。 I don't have time right now to re-hash every part of this, but this is exactly the problem I had a year ago when building a theme for a huge multisite network with some very old posts. 我现在没有时间重新散布其中的每个部分,但这正是我一年前为大型大型多站点网络构建主题时遇到的问题,其中包含一些非常古老的帖子。 The first function is the main one, and it calls some of the other ones to do various things. 第一个函数是主要函数,它调用其他一些函数来执行各种操作。 I'm pasting it here not as a complete answer, but as a resource or example for you to look through if you have the time. 我在这里粘贴的内容不是完整的答案,而是作为资源或示例,供您在有空的情况下浏览。 You may see some ways to fix or rebuild your function in here. 您可能会在此处看到一些修复或重建功能的方法。

Hope you find this helpful: 希望对您有所帮助:

/**
 * Gets the featured image.
 * If no featured image, picks up the first image in the post
 * If no images, default image is used
 *
 * @param int $post_id
 * @param bool $thumb_size
 * @param bool $return_all_images
 *
 * @return string|array Returns the url of the image to use, or an array if return_all_images is true
 */
function e3_featured_image($post_id, $thumb_size = false, $return_all_images = false) {
    $the_post = get_post($post_id);

    if ( ! $thumb_size ) {
        $thumb_size = 'e3-blog-featured-thumbnail';
    }

    if ( $the_post ) {
        $remote_images = $local_images = $remote_images_parsed = array();
        $thumbnail_url = '';

        if ( ! $thumbnail_url && $url = get_the_post_thumbnail_url( $the_post, $thumb_size ) ) {
            // The featured image is set. Use that.
            if ( ! $return_all_images ) {
                return $url;
            } else {
                $thumbnail_url = $url;
            }
        }

        // Now move on to checking the content
        if ( preg_match_all( "/<img\s[^>]*src=[\"']([^\"']*)[\"'][^>]*>/", $the_post->post_content, $matches ) ) {
            foreach ( $matches[1] as $key => $url ) {
                $components = parse_url( $url );
                $relative   = ( ! $components['host'] );

                if ( $relative || is_local_attachment( $url ) || strtolower( $components['host'] ) == strtolower( $_SERVER['HTTP_HOST'] ) ) {
                    // Ok, we've got a local image. Find it's attachment info.
                    $return = e3_featured_image_do_lookup( $matches[0][ $key ], $url, $thumb_size );
                    if ( $return && ! $return_all_images ) {
                        return $return;
                    } elseif ( $return ) {
                        $local_images[] = $return;
                        continue;
                    }

                    // Couldn't find the image in the database, so let's treat it as a remote image
                    $remote_images[] = $url;

                } else {
                    // Store remote image
                    $remote_images[] = $url;
                }
            }

        }

        if ( count( $remote_images ) > 0 ) {

            // There were no local images. Try getting a thumbnail from a remote image.
            foreach ( $remote_images as $image ) {
                $return = e3_get_remote_thumbnail( $image, $thumb_size );
                if ( $return && ! $return_all_images ) {
                    return $return;
                } elseif ( $return ) {
                    $remote_images_parsed[] = $return;
                    continue;
                }
            }

        }
    }

    if ( $return_all_images ) {
        $return_array = array();
        if ( ! empty( $thumbnail_url ) ) {
            $return_array['featured_image'] = $thumbnail_url;
        }
        if ( ! empty( $local_images ) ) {
            $return_array['local_images'] = $local_images;
        }
        if ( ! empty( $remote_images_parsed ) ) {
            $return_array['remote_images'] = $remote_images_parsed;
        }
        if ( !empty( $return_array) ) {
            return $return_array;
        }
    }

    // Still here? Return default image
    if ( file_exists( __DIR__ . "/img/default-{$thumb_size}.jpg") ) {
        return get_stylesheet_directory_uri() . "/img/default-{$thumb_size}.jpg";
    } else {
        return get_stylesheet_directory_uri() . '/img/default-blog-image.jpg';
    }

}

/**
 * See if we can find the db entry for an image so we can return the right thumb_size
 *
 * @param string $img_tag    The entire img tag
 * @param string $url        The URL of the image
 * @param string $thumb_size Thumbnail size (WP slug)
 *
 * @return bool|false|string
 */
function e3_featured_image_do_lookup($img_tag, $url, $thumb_size) {
    // First, try url_to_postid()
    if ( $id = url_to_postid($url) ) {

        $post = get_post( $id );
        if ( 'attachment' == $post->post_type ) {
            return wp_get_attachment_image_url( $id, $thumb_size );
        }
    }

    // Next, look for the WP class that has the ID in it
    if ( preg_match( "/wp-image-([0-9]+)/i", $img_tag, $class_match) ) {
        // We found the ID...
        $post = get_post( $class_match[1] );
        if ( 'attachment' == $post->post_type ) {
            return wp_get_attachment_image_url( $class_match[1], $thumb_size );
        }
    }

    // Try the guid
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%%%s%%';", $url ));
    $post = get_post($attachment[0]);
    if ( 'attachment' == $post->post_type ) {
        return wp_get_attachment_image_url( $attachment[0], $thumb_size );
    }
    return false;
}

/**
 * Returns the URL of a local copy of a remote image, sized appropriately
 *
 * @param string $url           URL of the remote image
 * @param string|array $size    An array where 0=>width (px), 1=>height (px) and 2=>crop (bool)
 *                              -OR-
 *                              Name of a WP registered timage size
 * @param null|bool $crop       Whether to crop the image to the exact size. Overrides crop value
 *                              of $size
 *
 * @return bool|string
 */
function e3_get_remote_thumbnail( $url, $size, $crop = null ) {
    if ( is_array($size) ) {
        if ( isset($size[0]) && isset($size[1]) ) {
            $width = intval($size[0]);
            $height = intval($size[1]);
            if ( isset( $size[2] ) && null == $crop ) {
                $crop = $size[2];
            }
        } else {
            // Size was an array, but we can't find the width/height
            return false;
        }
    } else {
        $sizes = wp_get_additional_image_sizes();
        if ( isset( $sizes[$size] ) ) {
            $width = intval($sizes[$size]['width']);
            $height = intval($sizes[$size]['height']);
            $crop = ($crop === null) ? $sizes[$size]['crop'] : $crop;
        } else {
            // Size wasn't an array and didn't match any registered image sizes. Give up.
            return false;
        }
    }
    if ( ! $width && ! $height ) {
        //Can't make an image with no width or height.
        return false;
    }

    // Figure out filenames
    $width_text = $width ? $width : '_';
    $height_text = $height ? $height : '_';
    $crop = $crop ? '1' : '0';
    $extension = strtolower( substr($url, strripos($url, '.') + 1) );
    if ( ! in_array( $extension, array('jpg', 'jpeg', 'png', 'gif') ) ) {
        // Not a supported image type (jpeg, png or gif).
        return false;
    }
    $upload_dir = wp_upload_dir();
    if ( ! file_exists( $upload_dir['basedir'] . '/cache' ) ) {
        mkdir( $upload_dir['basedir'] . '/cache' );
    }
    if ( ! file_exists( $upload_dir['basedir'] . '/cache/e3_external_thumbs/' ) ) {
        mkdir( $upload_dir['basedir'] . '/cache/e3_external_thumbs/' );
    }
    $cache_file_ending = '/cache/e3_external_thumbs/' . md5($url) . "-$height_text-$width_text-$crop.$extension";
    $cache_file_path = $upload_dir['basedir'] . $cache_file_ending;
    $cache_file_uri = $upload_dir['baseurl'] . $cache_file_ending;

    // Check cache for this url and size
    if ( file_exists($cache_file_path) ) {
        if ( 0 == filesize($cache_file_path) ) {
            // This file has been cached as an empty file. Just return false because it seems like a bad link
            return false;
        }
        return $cache_file_uri;
    }

    // Get, resize, cache and return the remote image

    // --Get
    $file = file_get_contents( $url );
    if ( ! $file ) {
        // Looks like the image doesn't exist. Save a blank file to keep this from gumming up the works on every page load
        file_put_contents($cache_file_path, '');
        return false;
    } else {
        file_put_contents('tmp.image', $file );
    }

    // --Resize and cache
    $crop_result = e3_resize_crop_image($width, $height, 'tmp.image', $cache_file_path, $crop );
    if ( file_exists( 'tmp.image' ) ) {
        unlink( 'tmp.image' );
    }

    if ( ! $crop_result ) {
        // The crop failed due to mime type problem. Save a blank file
        file_put_contents($cache_file_path, '');
        return false;
    }

    // --Return
    return $cache_file_uri;
}


/**
 * Resize/Crop and save an image
 *
 * @param int $max_width        Width (or max width if crop is false) for new image
 * @param int $max_height       Height (or max height if crop is false) for new image
 * @param string $source_file   Image to crop
 * @param string $dst_file      Path and filename to save the new image to
 * @param bool $crop            Whether to crop to exact dimensions
 *
 * @return bool
 */
function e3_resize_crop_image($max_width, $max_height, $source_file, $dst_file, $crop){
    $quality = 80;
    $imgsize = getimagesize($source_file);
    $width = $imgsize[0];
    $height = $imgsize[1];
    if ( ! $max_height ) {
        $max_height = $max_width * $height / $width;
    }
    if ( ! $max_width ) {
        $max_width = $max_height * $width / $height;
    }
    $mime = $imgsize['mime'];
    if ( $width < $max_width && $height < $max_height ) {
        copy( $source_file, $dst_file );
        if ( file_exists( 'tmp.image' ) ) {
            unlink( 'tmp.image' );
        }
        return true;
    }

    switch($mime){
        case 'image/gif':
            $image_create = "imagecreatefromgif";
            $image = "imagegif";
            break;

        case 'image/png':
            $image_create = "imagecreatefrompng";
            $image = "imagepng";
            $quality = 7;
            break;

        case 'image/jpeg':
            $image_create = "imagecreatefromjpeg";
            $image = "imagejpeg";
            break;

        default:
            return false;
            break;
    }

    $dst_img = imagecreatetruecolor( $max_width, $max_height );
    // set background to white
    $white = imagecolorallocate($dst_img, 255, 255, 255);
    imagefill($dst_img, 0, 0, $white);

    $src_img = $image_create($source_file);

    $ratio = $width / $height;
    $new_ratio = $max_width / $max_height;

    if ( $ratio == $new_ratio ) {
        // Same ratio, just resize
        imagecopyresampled( $dst_img, $src_img, 0, 0, 0, 0, $max_width, $max_height, $width, $height );
    } elseif ( ! $crop ) {
        // Don't crop the image. Just resize to fit inside the box
        if ( $ratio > $new_ratio ) {
            // Image is wider than the new image
            // New image has requested width, but a reduced height
            $new_height = floor( $max_width / $ratio );
            $top = round( ($max_height - $new_height) / 2 );
            //$dst_img = imagecreatetruecolor( $max_width, $new_height );
            imagecopyresampled( $dst_img, $src_img, 0, $top, 0, 0, $max_width, $new_height, $width, $height );
        } else {
            // Image is taller than the new image
            // New image has requested height, but a reduced wodth
            $new_width = floor( $max_height * $ratio );
            $left = round( ($max_width - $new_width) / 2 );
            //$dst_img = imagecreatetruecolor( $new_width, $max_height );
            imagecopyresampled( $dst_img, $src_img, $left, 0, 0, 0, $new_width, $max_height, $width, $height );
        }
    } else {
        // Crop the image to fit exactly
        if ( $ratio > $new_ratio ) {
            // Image is wider than the new image
            // Keep the height and crop the sides off
            $new_original_width = floor( $height * $new_ratio );
            $horizontal_cut_point = ($width - $new_original_width) / 2;
            imagecopyresampled( $dst_img, $src_img, 0, 0, $horizontal_cut_point, 0, $max_width, $max_height, $new_original_width, $height );
        } else {
            // Image is taller than the new image
            // keep the width and crop the top and bottom off
            $new_original_height = floor( $width / $new_ratio );
            $vertical_cut_point = ($height - $new_original_height) / 2;
            imagecopyresampled( $dst_img, $src_img, 0, 0, 0, $vertical_cut_point, $max_width, $max_height, $width, $new_original_height );
        }
    }

    $image( $dst_img, $dst_file, $quality );

    if ( $dst_img ) {
        imagedestroy($dst_img);
    }
    if ( $src_img ) {
        imagedestroy($src_img);
    }
    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM