To set a thumbnail for product you can't pass the argument post_thumbnail
to wp_insert_post
it does nothing.
The right way is to use the wp function set_post_thumbnail
. Problem is that to use this function you need the ID of the image, not the url.
Once you in your code use get_field
I assumed that you are using ACF plugin, and that the field imagem_do_produto
in an 'image' field type that upload images in media library and, by default, save the url as custom field.
That field can be configured to save the image id, that it's better for your scope, but once you say that it contain an url you need to get the image id from its url.
A rapid google search let me find a good solution for that here.
Now we can use the function we find and put it in functions.php
, then make use of it in combination with set_post_thumbnail
to assign the thumbnail to the newly created post.
<?php
// this function should go in functions.php
// and is not needed if your imagem_do_produto is configured to save the ID
function image_id_from_url( $attachment_url = '' ) {
if ( empty($attachment_url) || ! filter_var($thumb, FILTER_VALIDATE_URL ) )
return false;
$upload_dir_paths = wp_upload_dir();
if ( ! substr_count($attachment_url, $upload_dir_paths['baseurl']) )
return false;
$attachment_id = false;
$attachment_url = preg_replace( '/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url );
$attachment_url = str_replace( $upload_dir_paths['baseurl'] . '/', '', $attachment_url );
global $wpdb;
$attachment_id = $wpdb->get_var( $wpdb->prepare(
"SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = '_wp_attached_file'
AND wpostmeta.meta_value = '%s'
AND wposts.post_type = 'attachment'",
$attachment_url
) );
return $attachment_id;
}
If you configure your image field to save the image id instead of the url, the function above is not needed.
$exists = get_page_by_title( get_field('fornecedor'), OBJECT, 'fornecedores');
$postid = '';
if( empty($exists) ) {
$insert_post = array(
'post_status' => 'publish',
'post_type' => 'fornecedores',
'post_title' => get_field('fornecedor'),
);
$postid = wp_insert_post($insert_post);
}
if ( ! empty($postid) ) {
// if you configure the field 'imagem_do_produto' to save image id
// replace next 2 lines with only one:
// $thumbnail_id = get_field('imagem_do_produto');
$thumbnail_url = get_field('imagem_do_produto');
$thumbnail_id = image_id_from_url( $thumbnail_url );
if ( $thumbnail_id > 0 ) set_post_thumbnail( $postid, $thumbnail_id );
}