David Barrios-Urzúa
Lucio Negrello
Ricardo Carranza
Lucio Negrello
Juanito Ortega Guzmán
Lucio Negrello
Juanito Ortega Guzmán
Juanito Ortega Guzmán
Juanito Ortega Guzmán
Lo que se me ocurrió hacer para mi bloque fue un bloque sencillo que pueda funcionar como un Call to Action dinámico, para usarse en artículos de blog o en páginas del sitio:
Éste tiene un título, un texto y un botón. El usuario puede elegir el título, el texto, el texto del botón y el link del botón.
Comencé haciendo un CodePen de mi bloque, para ver los dos estilos y generar el markup necesario. Ahí puede verse el html y el scss de mi bloque.
Mi edit.js terminó viéndose así:
import {InspectorControls} from "@wordpress/block-editor"; import {Panel, PanelBody, TextControl, TextareaControl} from "@wordpress/components"; const Edit = (props) => { const {className, attributes, setAttributes} = props; const {title, text, buttonText, buttonLink} = attributes; return( <> <InspectorControls> <Panel> <PanelBody title="CTA Options" initialOpen={true}> <TextControl label= "Title" value= {title} onChange= {(newTitle) => setAttributes({title: newTitle})} /> <TextareaControl label= "CTA Text" help= "Please, enter the text for the CTA" value= {text} onChange= {(newText) => setAttributes({text: newText})} /> <TextControl label="Button text" value= {buttonText} onChange={(newButtonText) => setAttributes({buttonText: newButtonText})} /> <TextControl label="Button link" value= {buttonLink} onChange={(newButtonLink) => setAttributes({buttonLink: newButtonLink})} /> </PanelBody> </Panel> </InspectorControls> <div className={className}> <h2 className="cta__title"> {title} </h3> <p className="cta__text"> {text} </p> <button type="button" className="cta__btn" href={buttonLink}> {buttonText} </button> </div> </> ); } export default Edit;
Vi que adicional a "TextControl", existe "TextareaControl", así que lo importé también porque me pareció un input más adecuado para la longitud del copy que un user podría añadir en el campo "CTA text".
Mi index.php luce así:
<?php add_action('init', 'plz_cta_blocks'); function plz_cta_blocks(){ $assets_file = include_once PLZ_PATH . "/blocks/cta/build/index.asset.php"; wp_register_script( 'plz-cta-block', plugins_url('./build/index.js', __FILE__), $assets_file['dependencies'], $assets_file['version'] ); wp_register_style( "g-font", "https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700", array(), false, 'all'); wp_register_style( 'plz-cta-block', plugins_url('./build/index.css', __FILE__), array('g-font'), $assets_file['version'] ); register_block_type( 'plz/cta', array( 'editor_script' => 'plz-cta-block', 'style' => 'plz-cta-block' )); }
Incluí la fuente porque aunque esta se carga en el front end desde el theme, no era visible en el editor, pero no sé si este sea el procedimiento ideal para esto.
Así se ven las opciones del bloque desde el editor:
Y así es como se ven los dos estilos del bloque en el front end:
Muchas gracias Lucio, tenía bastante tiempo tratando de aprender todo este proceso!
Woooow, David!!! Escelente trabajo, que bueno que hayas podido armarlo y, además, investigar un poco más por tu cuenta. Felicitaciones!!!
Estoy usando la version 6.0.2 de wordpress y no aparecen las vistas previas automaticamente:
Es posible en esta version de wordpress generar esa vista previa automaticamente ? y sino Se puede configurar esta vista previa para mostrar una imagen personalizada?
Hola mateo, cómo estás? Me parece que en esta versión intentaron simplificar la interface y los diferentes estilos se ven al aplicarse, directamente sobre el bloque. No estoy seguro si hay una vista rpevia cuando se mantiene el hover con el mouse. Por otro lado, desde los estilos no se podría generar la vista previa con una imagen personalizada, pero creando tu propia interfaz de bloque seguramente sí. Es más complejo porque no podrías aprovechar la simplicidad de agregar los estilos, pero se debería poder si desarrollas el componente con la vista rpevia. Saludos!
Cómo cargas las miniaturas para seleccionar el Dark mode o Light mode?...
Hola Juanito, cómo estás? No se cargan, se generan automaticamente como vista previa de los estilos aplicados al bloque. Cuando se compila con los estilos y toda la interface se comienzan a ver automaticamente. Saludos!
Hola Lucio, te cuento que en mi caso no se generan, solo veo algo vacío.
Me di a la tarea de hacer el bloque para el login, seguí la misma lógica que para el registro. Creé una carpeta login dentro de blocks y edité mi archivo package.json de esta forma:
"scripts": { "build": "wp-scripts build", "build:login": "wp-scripts build ./login/src/index.js --output-path=./login/build", "check-engines": "wp-scripts check-engines", "check-licenses": "wp-scripts check-licenses", "format": "wp-scripts format", "lint:css": "wp-scripts lint-style", "lint:js": "wp-scripts lint-js", "lint:md:docs": "wp-scripts lint-md-docs", "lint:md:js": "wp-scripts lint-md-js", "lint:pkg-json": "wp-scripts lint-pkg-json", "packages-update": "wp-scripts packages-update", "start": "wp-scripts start", "start:login": "wp-scripts start ./login/src/index.js --output-path=./login/build", "test:e2e": "wp-scripts test-e2e", "test:unit": "wp-scripts test-unit-js" },
login/src/edit.js
import { useState } from '@wordpress/element'; import { BlockControls, InspectorControls, RichText } from '@wordpress/block-editor'; import { Panel, PanelBody, TextControl } from '@wordpress/components'; const Edit = (props) => { const { className, attributes, setAttributes } = props; const { title, emailLabel, passLabel, text } = attributes; const [hasText, setHasText] = useState(text); return ( <> <InspectorControls> <Panel> <PanelBody title="Labels" initialOpen={true}> <TextControl label="Email Label" value={emailLabel} onChange={(newLabel) => setAttributes({ emailLabel: newLabel })} /> <TextControl label="Password Label" value={passLabel} onChange={(newLabel) => setAttributes({ passLabel: newLabel })} /> </PanelBody> </Panel> </InspectorControls> <BlockControls controls={[ { icon: 'text', title: 'Add text', isActive: text || hasText, onClick: () => setHasText(!hasText) } ]} /> <div className={className}> <div className="signin__container"> <RichText tagName="h1" placeholder="Escribe un título" className="signin__titulo" value={title} onChange={(newTitle) => setAttributes({ title: newTitle })} /> {(text || hasText) && <RichText tagName="p" placeholder="Escribe un párrafo" value={text} onChange={(newText) => setAttributes({ text: newText })} /> } <form className="signin__form" id="signin"> <div className="signin__email name--campo"> <label htmlFor="email">{emailLabel}</label> <input name="email" type="email" id="email" /> </div> <div className="signin__pass name--campo"> <label htmlFor="password">{passLabel}</label> <input name="password" type="password" id="password" /> </div> <div className="signin__submit"> <input type="submit" value="Log In" /> </div> <div className="msg" /> </form> </div> </div> </> ); } export default Edit;
login/src/index.js
import { registerBlockType } from "@wordpress/blocks"; import edit from "./edit"; import save from "./save"; import "./styles.scss"; registerBlockType("plz/login", { title: "Login", category: "widgets", icon: "admin-users", attributes: { title: { source: "html", selector: "h1", default: "Login" }, emailLabel: { type: "string", default: "Email" }, passLabel: { type: "string", default: "Password" }, text: { source: "html", selector: "p" } }, styles: [ { name: "light", label: "Light Mode", isDefault: true }, { name: "dark", label: "Dark Mode" } ], edit, save });
login/src/save.js
import { RichText } from '@wordpress/block-editor'; const Save = (props) => { const { className, attributes } = props; const { title, emailLabel, passLabel, text } = attributes; return ( <div className={className}> <div className="signin__container"> <RichText.Content tagName="h1" className="signin__titulo" value={title} /> {text && <RichText.Content tagName="p" value={text} /> } <form className="signin__form" id="signin"> <div className="signin__email name--campo"> <label htmlFor="email">{emailLabel}</label> <input name="email" type="email" id="email" /> </div> <div className="signin__pass name--campo"> <label htmlFor="password">{passLabel}</label> <input name="password" type="password" id="password" /> </div> <div className="signin__submit"> <input type="submit" value="Log In" /> </div> <div className="msg" /> </form> </div> </div> ); } export default Save;
login/src/styles.scss
.wp-block-plz-login { min-height: 90vh; display: flex; align-items: center; justify-content: center; .signin__container { margin: 0 auto; display: block; max-width: 400px; width: 100%; margin: 20px 0; .signin__titulo { font-family: Quicksand; font-style: normal; font-weight: bold; font-size: 22px; line-height: 22px; color: #000000; margin-bottom: 40px; } .signin__form { .name--campo { display: flex; flex-direction: column; margin-bottom: 20px; label { font-family: Quicksand; font-style: normal; font-weight: bold; font-size: 14px; line-height: 17px; color: #000000; margin-bottom: 5px; } input:not([type=submit]) { background: #F7F7F7; border: 1px solid #F7F7F7; box-sizing: border-box; border-radius: 10px; height: 45px; font-family: Quicksand; font-style: normal; font-weight: normal; font-size: 16px; line-height: 20px; color: #797979; text-indent: 10px; &:focus { outline: none; } } } input[type=submit] { margin-top: 30px; background: #ACD9B2; border: 1px solid #ACD9B2; box-sizing: border-box; box-shadow: 0px 0px 4px rgba(0, 0, 0, 0.0001); border-radius: 10px; width: 100%; height: 55px; font-family: Quicksand; font-style: normal; font-weight: bold; font-size: 18px; line-height: 22px; text-align: center; color: #FFFFFF; transition: 200ms; &:hover { background-color: #000000; } &:focus { outline: none; } } .signin_create-link { margin-top: 30px; a { border: 1px solid #ACD9B2; box-sizing: border-box; filter: drop-shadow(0px 0px 4px rgba(0, 0, 0, 0.0001)); border-radius: 10px; width: 100%; height: 55px; display: inline-block; text-decoration: none; color: #ACD9B2; font-family: Quicksand; font-style: normal; font-weight: bold; font-size: 18px; line-height: 55px; text-align: center; transition: 200ms; &:hover { background-color: #000; color: white; } } } } } }
login/index.php
<?php function plz_login_blocks() { $assets_file = include_once PLZ_PATH . '/blocks/login/build/index.asset.php'; wp_register_script( 'plz-login-block', plugins_url( './build/index.js', __FILE__ ), $assets_file['dependencies'], $assets_file['version'] ); wp_register_style( 'plz-login-block', plugins_url( './build/index.css', __FILE__ ), array(), $assets_file['version'] ); register_block_type( 'plz/login', array( 'editor_script' => 'plz-login-block', 'script' => 'plz-login', 'style' => 'plz-login-block' ) ); } add_action( 'init', 'plz_login_blocks' );
Finalmente agregamos la siguiente línea en: plugin-frontend-login.php
require_once PLZ_PATH."/public/shortcode/form-login.php";
OJO: Me faltó los estilos del modo oscuro, por lo demás el form funciona. Saludos.
Corrección En el archivo plugin-frontend-login.php hay que agregar esta línea y no la línea que por error pegué en mi anterior mensaje.
require_once PLZ_PATH."/blocks/login/index.php";