la computadora del profesor esta muy lenta y no se graban las cosas bien en el video… no se entiende nada de lo que esta haciendo
Creando nuestro primer plugin
Presentación del curso
Cómo crear a partir de un Blueprint
Creando nuestro primer plugin
Armando la estructura del plugin
API y conexiones
Creando el formulario de registro de usuario
API REST en WordPress
Generando una conexión desde JS a nuestra API
Creando la API de registro
Creando la API de login
Funciones extras
Trabajando con roles de usuario
Mejorando nuestro código
Cierre del curso
Cómo puedo seguir aprendiendo
Tu opinión es importante, danos tu feedback
You don't have access to this class
Keep learning! Join and start boosting your career
Creating WordPress plugins is an exciting task that allows you to expand the functionality of a website. However, it is crucial to optimize the performance and readability of the code, avoiding redundancies and making the plugin adaptable to different environments. Here's how to achieve this.
One of the strategies to optimize your plugin is to avoid repetitive functions. This can be achieved by defining constants instead of variables or repeated functions. In PHP, the define
function is very useful. For example:
define('PLZ_PATHS', plugin_dir_path(__FILE__));
With the PLZ_PATHS
constant, we replace the plugin_dir_path
function in various parts of the code, making its execution unique and more efficient.
Dynamic URL handling is essential for the plugin to work correctly on different sites without the need to manually modify those addresses. When working with JavaScript in WordPress, we can make use of wp_localize_script
. This function is useful for passing PHP data to JavaScript:
wp_localize_script('login', 'plz', array( ' restUrl' => rest_url('plz/')));
Here we are creating a plz
object inside JavaScript that contains the restUrl
. This method allows you to define URLs dynamically and specific to your plugin.
Literal Strings
in JavaScript?When you are handling URLs in JavaScript, it is recommended to use literal strings
, making the code cleaner and easier to read. Here is an example:
const url = `${plz.restUrl}endpoint`;
Using string literals
eliminates the need to concatenate strings with the +
symbol, and complements proper object handling in JavaScript.
When registering a user, it is important that the role assigned is appropriate for each case. By default, the role should not be static, such as editor
; a role such as client
, mostly restricted, is preferable.
Modification in the registration API:
$new_user_id = wp_insert_user(array( ' role' => 'customer'));
This way, we ensure that new users get the proper permissions.
A best practice is to redirect the user after successful login. To do this, we can complement the check of responses obtained and perform a redirect.
if (jsonResponse === false) { window.location.href = plz.homeUrl;}
This way, we ensure that the user ends up on the desired page after successfully authenticating.
With these settings, you not only optimize your plugin in terms of code and functionality, but also ensure a consistent experience in different environments. Keep exploring and improving your WordPress development techniques to create robust and efficient solutions.
Contributions 13
Questions 4
la computadora del profesor esta muy lenta y no se graban las cosas bien en el video… no se entiende nada de lo que esta haciendo
Por favor Sres de Platzi, obsequien una mejor laptop al profesor para que pueda grabar bien los videos.
El video es bueno, pero falla al final en la imagen, dejo mi codigo de login.js es similar al que realizo el profe en la clase, el atributo usado para la redirección es window.location.href = ...
window.addEventListener("DOMContentLoaded",function(){
let $form = document.querySelector("#signin");
let $msg = document.querySelector(".msg");
$form.addEventListener("submit",function(e){
e.preventDefault();
let datos = new FormData($form);
let datosParse = new URLSearchParams(datos);
fetch(`${plz.rest_url}/login`,
{
method: "POST",
body: datosParse
}
)
.then(res=>res.json())
.then(json=>{
console.log(json)
if (json !== false) {
$msg.innerHTML = json
} else {
$msg.innerHTML = '<strong>Se ha loggeado correctamente 😎</strong>'
window.location.href = `${plz.home_url}`
}
})
.catch(err=>{
console.log(`Hay un error: ${err}`)
})
})
})
Buen video para cerrar el curso.
Lastima el detalle que por partes la pantalla no muestre lo que hace el profesor.
Se traba mucho la grabación de la pantalla y no permite ver bien el paso a paso.
Muy bueno el curso, lo único es que me genera ansiedad la lentitud de la computadora o grabación de la pantalla del profesor. Se ve muy lag que no permite ver con comodidad cada paso que realiza.
Que cursito pesado, con el retraso que tienen los videos la mitad de las cosas no se ven.
Les dejo una propuesta para lograr redireccionar al home siempre y cuando se haya autenticado correctamente:
.then(json=>{
console.log(json)
$msg.innerHTML = json?.msg
if(json?.res==1) { location.href= `${pnet.home_url}`; }
})
Pero en el lado del API:
$user = wp_signon($args, false);
$result =null;
if( is_wp_error($user) )
{
$result = array(
'res' => 0,
'msg' => "Error al autenticar usuario, " . $user->get_error_message() );
}
else
{
$result = array(
'res' => 1,
'msg' => "El usuario se autenticó correctamente");
}
return $result;
fetch(`${plz.rest_url}/login`,
{
method: "POST",
body: datosParse
})
.then(res => res.json())
.then(json=>{
//la parte donde no se logra ver la corrección del profe
if(json = "false"){
window.location.href = `${plz.home_url}`
}else{
$msg.innerHTML = json?.msg
}
})
.catch(err=>{
console.log(`Hay un error: ${err}`)
})
No se vio la linea en la que se realizo la correccion
…terminando…
Want to see more contributions, questions and answers from the community?