在foreach循环中生成Wordpress精选图像,为多个帖子显示相同的图像

时间:2016-11-19 21:10:06

标签: php wordpress foreach youtube

晚上好。我已经编写了一个函数,使用foreach循环以编程方式为每个YouTube视频插入Wordpress帖子。

一切都工作得非常好,直到我插入帖子缩略图。我正在使用一个自动处理上传和插入缩略图的功能,并将其与帖子相关联(下方):

function Generate_Featured_Image($image_url, $post_id) {
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename = basename($post_id.'-'.$image_url);
    if (wp_mkdir_p($upload_dir['path']))     $file = $upload_dir['path'] . '/' . $filename;
    else                                     $file = $upload_dir['basedir'] . '/' . $filename;
    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => sanitize_file_name($filename),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $file, $post_id );

    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
    $res1 = wp_update_attachment_metadata( $attach_id, $attach_data );
    $res2 = set_post_thumbnail( $post_id, $attach_id );
}

此功能确实有效,但由于某些奇怪的原因,它只会上传循环中最后一个视频的图像。例如,如果我有5个视频,则会创建5个帖子。每个都包含它自己的特定信息,但是后缩略图将全部是最后一个(第5个)视频的图像。他们都没有自己的缩略图。

这是我职能部门的精简版,创造了帖子:

function createYouTubePost() {
    ...some other code...

    $JSON      = file_get_contents('https://www.googleapis.com/youtube/v3/search?order='.$api_order.'&part='.$api_part.'&channelId='.$channel_id.'&maxResults='.$max_results.'&key='.$api_key);
    $json_data = json_decode($JSON, true);

    foreach ($json_data['items'] as $data) {
        $video_id = $data['id']['videoId'];
        $video_title = $data['snippet']['title'];
        $video_description = $data['snippet']['description'];
        $video_thumb_url = $data['snippet']['thumbnails']['high']['url'];
        $video_thumb_width = $data['snippet']['thumbnails']['high']['width'];
        $video_thumb_height = $data['snippet']['thumbnails']['high']['height'];
        $video_publish_date = $data['snippet']['publishedAt'];

        $args = array(
            'post_title'   => substr($video_title, 0, strrpos($video_title, '(')),
            'post_content' => $video_description,
            'post_status'  => 'publish',
            'post_type' => 'download',
        );

        if (!if_download_exists(substr($video_title, 0, strrpos($video_title, '(')))) {
            $new_post_id = wp_insert_post($args, true);

            if ($new_post_id == 0) {
                echo '<br>Could not create the post.';
                var_dump($new_post_id);
            }
            else {
                Generate_Featured_Image($video_thumb_url, $new_post_id);

                ...lots of code to update various post_meta fields...

                echo '<br>New post created.<br>';
                var_dump($new_post_id);
            }
        }
    }
}

在这里,您可以看到媒体附件以及它们如何完全相同:

enter image description here

以下是创建的各个帖子:

enter image description here

如您所见,每个图像都分配给它的相应帖子,但图像是相同的。

我甚至尝试使用唯一ID设置每张图片的文件名,以便它们完全不同,但这并没有帮助。我还确认我传递给函数的图片网址都不同。

我的问题是,如果我在Generate_Featured_Image()循环中使用我的函数foreach,并使用唯一信息证明它,为什么它只使用循环中的最后一张图片?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我选择了其他解决方案。 WordPress的&#39; media_sideload_image()功能有效,对我的情况来说是一个更直接的解决方案。

以下是我现在用来为帖子分配缩略图的功能:

function generateFeaturedImage($image_url, $post_id) {
    // required libraries for media_sideload_image
    require_once(ABSPATH . 'wp-admin/includes/file.php');
    require_once(ABSPATH . 'wp-admin/includes/media.php');
    require_once(ABSPATH . 'wp-admin/includes/image.php');

    // $post_id == the post you want the image to be attached to
    // $video_thumb_url == the vimeo video's thumb url
    // $description == optional description

    // load the image
    $result = media_sideload_image($image_url, $post_id);

    // then find the last image added to the post attachments
    $attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));

    if (sizeof($attachments) > 0) {
        // set image as the post thumbnail
        set_post_thumbnail($post_id, $attachments[0]->ID);
    }
}

这里是the link我找到的堆栈交换解决方案。