Загруженное изображение не отображается в пользовательском типе записи
Я разрабатываю плагин, который должен позволять пользователям создавать пользовательский тип записи "reseller" и прикреплять изображение. Изображение загружается в папку uploads и появляется в медиатеке с пустой миниатюрой. Также изображение не отображается в списке 'resellers' в админке.
Может кто-то заметить, что я упустил? Соответствующие функции начинаются с строки 362 здесь:
https://gist.github.com/codecowboy/80fd6363c58558a74c9e
Релевантный участок кода:
public function wps_reseller_cpt() {
$labels = array(
'name' => _x( 'WPS Реселлеры', 'общее название для типа записи' ),
'singular_name' => _x( 'WPS Реселлер', 'название для одного экземпляра типа записи' ),
'add_new' => _x( 'Добавить новый', 'книга' ),
'add_new_item' => __( 'Добавить нового реселлера' ),
'edit_item' => __( 'Редактировать реселлера' ),
'new_item' => __( 'Новый реселлер' ),
'all_items' => __( 'Все реселлеры' ),
'view_item' => __( 'Просмотреть реселлера' ),
'search_items' => __( 'Искать реселлеров' ),
'not_found' => __( 'Реселлеры не найдены' ),
'not_found_in_trash' => __( 'В корзине нет реселлеров' ),
'parent_item_colon' => '',
'menu_name' => 'Реселлеры'
);
$args = array(
'labels' => $labels,
'description' => 'Содержит наших реселлеров и их данные',
'public' => true,
'menu_position' => 50,
'supports' => array( 'title', 'editor','image', 'thumbnail', 'custom-fields' ),
'has_archive' => false,
);
register_post_type( 'wps-reseller', $args );
}
public function create_reseller_profile_form(){
require_once plugin_dir_path( __FILE__ ) . 'views/public-create_reseller_profile_form.php';
}
public function intercept_reseller_profile_form() {
if ( !empty( $_POST['wps-reseller-user-submission'] ) ) {
$this->wps_reseller_process_form();
} else {
return $template;
}
}
public function wps_reseller_process_form() {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
if ( wp_verify_nonce( $_POST['reseller_user_form'], 'add_reseller_form') &&
!empty( $_POST['reseller-title'] ) &&
!empty( $_POST['reseller-description'] ) &&
!empty( $_FILES['reseller-image']) )
{
$file = $_FILES['reseller-image'];
$uploads = wp_upload_dir();
$new_reseller_profile_data = array(
'post_status' => 'draft',
'post_title' => $_POST['reseller-title'],
'post_content' => $_POST['reseller-description'],
'post_type' => 'wps-reseller'
);
$file_errors = $this->wps_parse_file_errors($file);
$upload_overrides = array( 'test_form' => FALSE );
if($file_errors['error'] == 0) {
if($new_reseller_id = wp_insert_post( $new_reseller_profile_data )){
$uploaded_file = wp_handle_upload( $file, $upload_overrides );
$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename( $uploaded_file['file'] ) ),
'post_content' => '',
'post_author' => '',
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_parent' => $new_reseller_id,
'guid' => $uploads['baseurl'] . $uploads['subdir'] . '/' . $file['name']
);
echo $uploads['baseurl'].'<br />';
echo $file['name'].'<br />';
var_dump($uploads); exit;
$attachment_id = wp_insert_post( $attachment );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploaded_file['file'] );
// Обновляем метаданные вложения
wp_update_attachment_metadata( $attachment_id, $attach_data );
set_post_thumbnail( $new_reseller_id, $attachment_id );
}
}
}
}
protected function wps_parse_file_errors($file){
define('MAX_UPLOAD_SIZE', 200000);
define('TYPE_WHITELIST', serialize(array(
'image/jpeg',
'image/png',
'image/gif'
)));
$result = array();
$result['error'] = 0;
if($file['error']){
$result['error'] = "Файл не загружен или произошла ошибка загрузки!";
return $result;
}
$image_data = getimagesize($file['tmp_name']);
if(!in_array($image_data['mime'], unserialize(TYPE_WHITELIST))){
$result['error'] = 'Ваше изображение должно быть в формате JPEG, PNG или GIF!';
}elseif(($file['size'] > MAX_UPLOAD_SIZE)){
$result['error'] = 'Размер вашего изображения: ' . $file['size'] . ' байт! Оно не должно превышать ' . MAX_UPLOAD_SIZE . ' байт.';
}
return $result;
}
}
Вопросы:
- Почему миниатюра пустая в медиатеке? Вот что загружается:
- Как сделать, чтобы изображение отображалось в интерфейсе администратора?
Если я добавляю файлы в библиотеку через медиаменеджер, миниатюры и изображения отображаются как положено.
Если это имеет значение, это мультисайтовая установка WordPress.

Попробуйте этот код для работы с вложениями
$uploaded_file = wp_handle_upload( $file, $upload_overrides );
$attachment = array(
'post_mime_type' => $uploaded_file['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename( $uploaded_file['file'] ) ),
'post_content' => '',
'post_author' => '',
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_parent' => $new_reseller_id,
'guid' => $uploaded_file['file']
);
$attachment_id = wp_insert_attachment( $attachment, $uploaded_file['file'] );
$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploaded_file['file'] );
// обновляем метаданные вложения
wp_update_attachment_metadata( $attachment_id, $attach_data );
//Устанавливаем как миниатюру
set_post_thumbnail ($new_reseller_id, $attachment_id );
Для получения миниатюры записи
Если вы находитесь в цикле, то
the_post_thumbnail
вернет вам изображение записи. В противном случае используйте
get_the_post_thumbnail ( $new_reseller_id )
