【问题标题】:Generating Wordpress featured image in foreach loop, showing same image for multiple posts在 foreach 循环中生成 Wordpress 特色图像,为多个帖子显示相同的图像
【发布时间】:2016-11-19 21:10:06
【问题描述】:

晚上好。我编写了一个函数,使用 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);
            }
        }
    }
}

您可以在此处查看媒体附件以及它们的相同之处:

以下是创建的各个帖子:

如您所见,每张图片都分配给它各自的帖子,但图片是相同的。

我什至尝试为每张图片的文件名设置一个唯一的 ID,以便它们都不同,但这没有帮助。我还确认了我传递给函数的图像 url 都是不同的。

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

感谢您的帮助!

【问题讨论】:

    标签: php wordpress foreach youtube


    【解决方案1】:

    我选择了另一种解决方案。 Wordpress 的 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多