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

时间:2019-03-13 17:51:28

标签: php wordpress

我正在使用以下代码从博客文章中提取第一张图片作为“精选图片”:

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');

它对于最近的博客帖子效果很好,但是较旧的帖子似乎无法撤消。我怀疑当时的主题模板可能在做一些不同的事情?我们正在尝试避免手动设置200幅以上的特色图像,并希望能够正常运行。

当我查看被拉取的图像的源代码时,它显示如下:

<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>

但是对于未拉动的对象,其显示如下:

<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>

对我来说,这表明它可能还有另一个模板。图像也可能嵌入在“ p”标签中。我尝试返回该帖子,并确保在原始帖子中图像周围的任何地方都没有

,并且没有。

1 个答案:

答案 0 :(得分:0)

好吧,这看起来像是一个巨大的数据转储,因为坦率地说就是这样。我现在没有时间重新散布其中的每个部分,但这正是我一年前为大型大型多站点网络构建主题时遇到的问题,其中包含一些非常古老的帖子。第一个函数是主要函数,它调用其他一些函数来执行各种操作。我在这里粘贴的内容不是完整的答案,而是作为资源或示例,供您在有空的情况下浏览。您可能会在这里看到一些修复或重建功能的方法。

希望这对您有所帮助:

/**
 * 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;
}