Imagen subida no aparece en tipo de publicación personalizada - Solución WordPress
Estoy escribiendo un plugin que debería permitir a los usuarios crear un tipo de publicación personalizada llamado "reseller" y adjuntar una imagen. La imagen se sube a la carpeta de uploads y aparece en la biblioteca de medios con una miniatura en blanco. La imagen tampoco es visible en la lista de 'resellers' en el backend, es decir, en la interfaz administrativa del tipo de publicación personalizada.
¿Alguien puede ver lo que me falta? Las funciones relevantes comienzan en la línea 362 aquí:
https://gist.github.com/codecowboy/80fd6363c58558a74c9e
Sección relevante:
public function wps_reseller_cpt() {
$labels = array(
'name' => _x( 'WPS Resellers', 'nombre general del tipo de publicación' ),
'singular_name' => _x( 'WPS Reseller', 'nombre singular del tipo de publicación' ),
'add_new' => _x( 'Añadir nuevo', 'book' ),
'add_new_item' => __( 'Añadir nuevo Reseller' ),
'edit_item' => __( 'Editar Reseller' ),
'new_item' => __( 'Nuevo Reseller' ),
'all_items' => __( 'Todos los Resellers' ),
'view_item' => __( 'Ver Reseller' ),
'search_items' => __( 'Buscar Resellers' ),
'not_found' => __( 'No se encontraron resellers' ),
'not_found_in_trash' => __( 'No hay Resellers en la papelera' ),
'parent_item_colon' => '',
'menu_name' => 'Resellers'
);
$args = array(
'labels' => $labels,
'description' => 'Contiene nuestros resellers y sus datos específicos',
'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']) )
{
//var_dump($_POST); exit;
$file = $_FILES['reseller-image'];
$uploads = wp_upload_dir();//var_dump($uploads); exit;
$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 )){
//$this->wps_process_image($file, $new_reseller_id);exit;
$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'] );
// actualizar los metadatos del adjunto
wp_update_attachment_metadata( $attachment_id, $attach_data );
set_post_thumbnail( $new_reseller_id, $attachment_id );
}
}
}
//crear un nuevo post reseller, hacerlo draft (asegurarse que el post type lo soporte)
//enviar email a un usuario admin
}
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'] = "¡No se subió ningún archivo o hubo un error en la subida!";
return $result;
}
$image_data = getimagesize($file['tmp_name']);
if(!in_array($image_data['mime'], unserialize(TYPE_WHITELIST))){
$result['error'] = '¡Tu imagen debe ser jpeg, png o gif!';
}elseif(($file['size'] > MAX_UPLOAD_SIZE)){
$result['error'] = 'Tu imagen era de ' . $file['size'] . ' bytes! No debe exceder ' . MAX_UPLOAD_SIZE . ' bytes.';
}
return $result;
}
Preguntas:
- ¿Por qué la miniatura está en blanco en la biblioteca de medios? Esto es lo que se está cargando:
- ¿Cómo hago para que la imagen aparezca en la interfaz de administración?
Si añado archivos a la biblioteca usando el gestor de medios, las miniaturas e imágenes aparecen como se espera.
En caso de que sea relevante, esta es una instalación multisite.

¿Qué tal si pruebas este código para tu adjunto?
$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'] );
// actualizar los metadatos del adjunto
wp_update_attachment_metadata( $attachment_id, $attach_data );
// Establecer como imagen destacada
set_post_thumbnail ($new_reseller_id, $attachment_id );
Para obtener la imagen destacada del post
Si estás dentro del bucle (loop), entonces
the_post_thumbnail
te dará la imagen destacada. De lo contrario, usa
get_the_post_thumbnail ( $new_reseller_id )
