Created
November 18, 2025 18:44
-
-
Save pochitax/f41f7bcd5e75194038ec2d27abe0cca9 to your computer and use it in GitHub Desktop.
Funciones para editar la API REST
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Agregar configuración de GraphQL */ | |
| add_action( 'graphql_register_types', function() { | |
| register_graphql_field( 'Post', 'nombreDelPersonaje', [ | |
| 'type' => 'String', | |
| 'description' => 'Campo Película de SCF', | |
| 'resolve' => function( $post ) { | |
| // Funciona con SCF porque SCF emula ACF | |
| return get_field('nombre_del_personaje', $post->ID); | |
| // o alternativamente: return get_post_meta($post->ID, 'pelicula', true); | |
| } | |
| ]); | |
| // Campo de texto | |
| register_graphql_field( 'Post', 'pelicula', [ | |
| 'type' => 'String', | |
| 'description' => 'pelicula', | |
| 'resolve' => function( $post ) { | |
| return get_field('pelicula', $post->ID); | |
| } | |
| ]); | |
| }); | |
| /* Agregar campos personalizados en la API REST */ | |
| add_action('init', function() { | |
| register_post_meta('post', 'pelicula', [ | |
| 'type' => 'string', | |
| 'single' => true, | |
| 'show_in_rest' => true, | |
| ]); | |
| register_post_meta('post', 'imagen', [ | |
| 'type' => 'integer', | |
| 'single' => true, | |
| 'show_in_rest' => true, | |
| ]); | |
| register_post_meta('post', 'nombre_del_personaje', [ | |
| 'type' => 'string', | |
| 'single' => true, | |
| 'show_in_rest' => true, | |
| ]); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Document</title> | |
| <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-LN+7fdVzj6u52u30Kp6M/trliBMCMKTyK833zpbD+pXdCLuTusPj697FH4R/5mcr" crossorigin="anonymous"> | |
| <link rel="stylesheet" href="./assets/css/style.css"> | |
| </head> | |
| <body> | |
| <header class="p-4 text-center"> | |
| <h1>Wordpress headless</h1> | |
| </header> | |
| <main class="container"> | |
| <h2>Creando entradas en la api Rest</h2> | |
| <p class="mb-4">Vamos a crear post en nuestro sitio web, interviniendo la API Rest de Wordpress.</p> | |
| <!-- FORMULARIO SIMPLE --> | |
| <form class="mb-4"> | |
| <!-- titulo --> | |
| <label class="form-label" for="titulo">Título del post</label> | |
| <input id="titulo" class="form-control mb-4" placeholder="Ingresa el título de tu entrada"> | |
| <!-- campo personalizado de pelicula --> | |
| <label class="form-label" for="peliFavorita">Película favorita</label> | |
| <input id="peliFavorita" class="form-control mb-4" placeholder="Ingresa la película favorita"> | |
| <!-- nombre del personaje --> | |
| <label class="form-label" for="nombrePersonaje">Nombre del personaje</label> | |
| <input id="nombrePersonaje" class="form-control mb-4" placeholder="Ingresa el nombre de tu personaje"> | |
| <!-- imagen destacada post --> | |
| <label class="form-label" for="imagenDestacada">Ruta de la imagen</label> | |
| <input id="imagenDestacada" class="form-control mb-4" type="file" placeholder="Sube tu imagen"> | |
| <!-- contenido de la entrada --> | |
| <label class="form-label" for="contenido">Contenido de la entrada</label> | |
| <textarea id="contenido" class="form-control mb-4" placeholder=""></textarea> | |
| <button class="btn btn-primary" id="btnCrear">Crear Post</button> | |
| </form> | |
| <!-- listado extraido directamente de la api Rest --> | |
| <div class="row" id="listadoEntradas"> | |
| </div> | |
| </main> | |
| <!--<script src="./assets/js/retornar-token.js"></script>--> | |
| <!-- JQUERY --> | |
| <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script> | |
| <!-- Funciones headless --> | |
| <script src="./assets/js/script-token.js"></script> | |
| <script src="./assets/js/script-new-post.js"></script> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ==== TOKEN JWT ==== | |
| const TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0Ojg4ODgvd3AtaGVhZGxlc3Mvd29yZHByZXNzIiwiaWF0IjoxNzYzMTI0MTQ5LCJuYmYiOjE3NjMxMjQxNDksImV4cCI6MTc2MzcyODk0OSwiZGF0YSI6eyJ1c2VyIjp7ImlkIjoiMSJ9fX0.xbR_E4g9Or4mgkGSdVsujL9KAIZX0n0X5VgIQh4Re-k"; | |
| // COMO OBTENER EL TOKEN REAL EN LA CONSOLA | |
| /* | |
| curl -X POST \ | |
| -d "username=admin&password=admin123" \ | |
| http://localhost:8888/wp-headless/wordpress/wp-json/jwt-auth/v1/token | |
| */ | |
| async function subirImagen(file) { | |
| const formData = new FormData(); | |
| formData.append("file", file); | |
| const res = await fetch("http://localhost:8888/wp-headless/wordpress/wp-json/wp/v2/media", { | |
| method: "POST", | |
| headers: { | |
| "Authorization": "Bearer " + TOKEN | |
| }, | |
| body: formData | |
| }); | |
| const data = await res.json(); | |
| return data.id; // ← ESTE es el ID correcto que SCF necesita | |
| } | |
| // ==== FUNCIÓN PARA CREAR UN POST ==== | |
| function crearPost(titulo, contenido, peliFav, nombrePersonaje, imagenPost) { | |
| const data = { | |
| title: titulo, | |
| content: contenido, | |
| status: "publish", // o "draft" | |
| meta: { | |
| pelicula: peliFav, | |
| nombre_del_personaje: nombrePersonaje, | |
| imagen: imagenPost | |
| } | |
| }; | |
| return fetch("http://localhost:8888/wp-headless/wordpress/wp-json/wp/v2/posts", { | |
| method: "POST", | |
| headers: { | |
| "Content-Type": "application/json", | |
| "Authorization": "Bearer " + TOKEN | |
| }, | |
| body: JSON.stringify(data) | |
| }) | |
| .then(res => res.json()) | |
| .then(data => { | |
| console.log("POST CREADO:", data); | |
| return data; | |
| }) | |
| .catch(err => console.error("Error creando post:", err)); | |
| } | |
| document.addEventListener("DOMContentLoaded", () => { | |
| document.getElementById("btnCrear").addEventListener("click", async (e) => { | |
| e.preventDefault(); | |
| const titulo = document.getElementById("titulo").value; | |
| const contenido = document.getElementById("contenido").value; | |
| const peliFav = document.getElementById("peliFavorita").value; | |
| const personajeFav = document.getElementById("nombrePersonaje").value; | |
| const archivoImagen = document.getElementById("imagenDestacada").files[0]; | |
| let imagenPost = null; | |
| // Solo sube imagen si el usuario seleccionó un archivo | |
| if (archivoImagen) { | |
| imagenPost = await subirImagen(archivoImagen); | |
| console.log("ID de imagen subida:", imagenPost); | |
| } | |
| await crearPost(titulo, contenido, peliFav, personajeFav, imagenPost); | |
| setTimeout(() => { | |
| mostrarPost(); | |
| }, 200); | |
| // limpiar form | |
| document.querySelector("form.mb-4").reset(); | |
| }); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // MODIFICACIÓN DEL SCRIPT PARA QUE SE PUEDAN VER LOS CAMPOS PERSONALIZADOS INGRESADOS EN LA API REST | |
| // FUNCIÓN PARA OBTENER EL TOKEN | |
| function obtenerToken() { | |
| return fetch('http://localhost:8888/wp-headless/jwt.php') | |
| .then(response => response.json()) | |
| .then(data => { | |
| if (data.error) throw new Error(data.error); | |
| if (!data.token) throw new Error("No se recibió un token válido."); | |
| return data.token; | |
| }); | |
| } | |
| // FUNCIÓN PARA TRAER LOS POSTS | |
| function obtenerPost(token) { | |
| return fetch('http://localhost:8888/wp-headless/wordpress/wp-json/wp/v2/posts', { | |
| method: 'GET', | |
| headers: { | |
| 'Authorization': `Bearer ${token}`, | |
| 'Content-Type': 'application/json' | |
| }, | |
| }) | |
| .then(response => { | |
| if (!response.ok) throw new Error("Error al obtener los posts: " + response.status); | |
| return response.json(); | |
| }); | |
| } | |
| // MOSTRAR LOS POSTS | |
| function mostrarPost() { | |
| obtenerToken() | |
| .then(token => obtenerPost(token)) | |
| .then(posts => { | |
| const postLista = document.getElementById('listadoEntradas'); | |
| postLista.innerHTML = ''; | |
| posts.forEach(post => { | |
| const columna = document.createElement('div'); | |
| columna.classList.add('col-md-3') | |
| const secureCustomField = post.acf?.pelicula // pelicula | |
| const secureCustomFieldPersonaje = post.acf?.nombre_del_personaje // nombre | |
| const secureCustomFieldImagen = post.acf?.imagen_source?.formatted_value // imagen | |
| // valor para la imagen | |
| let imagenEntrada; | |
| if(secureCustomFieldImagen != false){ | |
| imagenEntrada = `<img src="${secureCustomFieldImagen.url}" class="w-100 mb-4">` | |
| } else { | |
| imagenEntrada = '' | |
| } | |
| // valor para el personaje | |
| let personajeEntrada; | |
| if(secureCustomFieldPersonaje != ''){ | |
| personajeEntrada = `El personaje favorito es ${secureCustomFieldPersonaje}` | |
| } else { | |
| personajeEntrada = 'El autor del post no ha declarado su personaje' | |
| } | |
| // valor para la pelicula | |
| let personajePelicula; | |
| if(secureCustomField != ''){ | |
| personajePelicula = `La película favorita es ${secureCustomField}` | |
| } else { | |
| personajePelicula = 'El autor del post no ha declarado su pelicula favorita' | |
| } | |
| columna.innerHTML = `<div class="p-4 border mb-4"> | |
| ${imagenEntrada} | |
| <h3>${post.title.rendered}</h3> | |
| <p>La película favorita del autor es <span class="text-warning">"${personajePelicula}"</span>.</p> | |
| <span>El personaje favorito es ${personajeEntrada}.</span> | |
| </div>` | |
| postLista.appendChild(columna); | |
| }); | |
| }) | |
| .catch(error => console.error('Error: ', error)); | |
| } | |
| mostrarPost(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment