要为产品设置缩略图,无法传递参数post_thumbnail
到wp_insert_post
它什么都不做。
正确的方法是使用wp功能set_post_thumbnail
. 问题是要使用此函数,您需要的是图像的ID,而不是url。
一旦您在代码中使用get_field
我以为你在使用ACF plugin, 那场比赛imagem_do_produto
在\'image\' field type 在媒体库中上载图像,默认情况下,将url另存为自定义字段。
该字段可以配置为保存image id, 这对您的范围更好,但一旦您说它包含url,您就需要从其url获取图像id。快速的谷歌搜索让我找到了一个很好的解决方案here.
现在我们可以使用我们找到并放入的函数functions.php
, 然后将其与set_post_thumbnail
将缩略图分配给新创建的帖子。
<?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;
}
如果将图像字段配置为保存图像id而不是url,则不需要上述功能。
$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 );
}