php - 在foreach循环中生成Wordpress特色图片,为多个帖子显示同一图片

标签 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,以使它们都不同,但这并没有帮助。我还确认了我传递给函数的图像URL都是不同的。

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

谢谢你的帮助!

最佳答案

我提出了另一种解决方案。 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

关于php - 在foreach循环中生成Wordpress特色图片,为多个帖子显示同一图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40697940/

相关文章:

PHP 错误 `Only variables should be passed by reference`

是否使用PHP框架(Cake PHP)

javascript - 如何检查一个对象数组是否包含另一个对象数组的所有ID JS

php - 在大型数据集上使用 orderby 时 MySQL 查询花费的时间太长

php - mysql 查询获取一些表/数组

php - 无法使用数组更新帖子元

wordpress - 使用 htaccess 去除 wp-admin 品牌

php - WordPress 以 Posts foreach 循环中的最后一项为目标

node.js - 如何在nodejs中使用foreach进行Mongodb操作

php - 使用 PHP 查询 SQL Server 数据库