- Crear un cpt Selfie
- Crear un boton con html
style
.btn-selfie{
padding:15px 30px;
font-size:18px;
border:2px solid #ffffff;
border-radius:8px;
background:transparent;
color:#ffffff;
cursor:pointer;
transition:all 0.3s ease;
}
.btn-selfie:hover{
background:#2A0505;
color:#ffffff;
border-color:#2A0505;
}
const btn = document.getElementById(“btnCamara”);
const input = document.getElementById(“inputCamara”);
btn.addEventListener(“click”, () => input.click());
input.addEventListener(“change”, function() {
if(!this.files.length) return;
const formData = new FormData();
formData.append(“action”, “subir_selfie”);
formData.append(“foto”, this.files[0]);
fetch(window.location.origin + “/wp-admin/admin-ajax.php”, {
method: “POST”,
body: formData
})
.then(response => response.json())
.then(data => {
if(data.success){
window.location.href = “https://paoparty.com.ar/galeria-selfie/”;
} else {
alert(“Error al subir la imagen.”);
}
})
.catch(error => {
console.error(“Error:”, error);
alert(“Error al subir la imagen.”);
});
});
/script
Luego un snippet
add_action(‘wp_ajax_nopriv_subir_selfie’, ‘procesar_selfie’);
add_action(‘wp_ajax_subir_selfie’, ‘procesar_selfie’);
function procesar_selfie(){
if(empty($_FILES[‘foto’])){
wp_send_json_error();
}
require_once(ABSPATH . ‘wp-admin/includes/file.php’);
require_once(ABSPATH . ‘wp-admin/includes/media.php’);
require_once(ABSPATH . ‘wp-admin/includes/image.php’);
// Subir imagen a la biblioteca
$attachment_id = media_handle_upload(‘foto’, 0);
if(is_wp_error($attachment_id)){
wp_send_json_error();
}
// Crear post en CPT selfie
$post_id = wp_insert_post([
‘post_title’ => ‘Selfie ‘ . current_time(‘d/m/Y H:i’),
‘post_status’ => ‘publish’,
‘post_type’ => ‘selfie’
]);
if(is_wp_error($post_id)){
wp_send_json_error();
}
// Asignar imagen destacada
set_post_thumbnail($post_id, $attachment_id);
wp_send_json_success();
}