使用新的缩略图PHP设置Woocommerce产品缩略图

时间:2018-07-31 05:11:14

标签: php wordpress woocommerce thumbnails product

我创建了一个自定义插件来导入和导出woocommerce产品。我遇到一个问题,当我尝试导入CSV时,产品的缩略图已更改并设置为较旧的缩略图,而这些缩略图是早先添加到产品中的。

我在CSV中有完整的图片网址。这是我的导入代码:

    $product_img = $row[13]; //Product Image
    $res = $wpdb->get_results('select post_id from ' . $wpdb->prefix . 'postmeta where meta_value like "%' . basename($product_img). '%"');
    if(count($res) == 0)
    {
        $res = $wpdb->get_results('select ID as post_id from ' . $wpdb->prefix . 'posts where guid="' . $product_img . '"');
    }
    $thumbnail_id = $res[0]->post_id;

    set_post_thumbnail( $product_id, $thumbnail_id );
    $attach_data = wp_generate_attachment_metadata( $thumbnail_id, $product_img );
    wp_update_attachment_metadata( $thumbnail_id,  $attach_data );

谁能告诉我我错了,为什么缩略图会随着旧的而更新。我正在尝试从过去1天开始发现问题,但尚未发现。

谢谢。

1 个答案:

答案 0 :(得分:0)

我发现了错误。第一个查询返回所有匹配的结果,并选择第一个帖子ID,因此它返回第一个匹配的帖子ID。代码应类似于:

$product_img = $row[13]; //Product Image

    $res = $wpdb->get_results('select ID as post_id from ' . $wpdb->prefix . 'posts where guid="' . $product_img . '"');

$thumbnail_id = $res[0]->post_id;

set_post_thumbnail( $product_id, $thumbnail_id );

这很好。