Professional Documents
Culture Documents
WP Hooks
WP Hooks
WP Hooks
Nucleo
Temas
Plugins
Ganchos: (Hooks)
Acciones y Filtros
3 Ganchos básicos
register_activation_hook( )
register_deactivation_hook( )
register_uninstall_hook( )
WordPress API
APIs Básicas
Plugin API
Options API
Settings API
HTTP API
Shortcode API
Requisitos de cabecera
Comentario de cabecera
/*
Plugin Name: Nombre del plugin
Plugin URI: http://miplugin.com/
Description: Éste plugin cambia el título
Version: 1.0
Author: Gilbert Rodríguez
Author URI: https://beziercode.com.co
License: GPL
License URI: http://
Text Domain: miplugin-beziercode
Domain Path: /languages/
*/
Ganchos (Hooks)
Activación y Desactivación
register_activation_hook( string $file, callable $function );
uninstall.php
Mejores Prácticas
Evitar conflictos de nombres
$prefijo_nombrevariable=’’;
function prefijo_nombrefuncion(){}
class Prefijo_NombreClase {}
Mejores Prácticas
Comprobar existencias
Variables: isset()
Funciones: function_exists()
Clases: class_exists()
Constantes: defined()
Mejores Prácticas
Estructura de carpetas
plugin-name
plugin-name.php
uninstall.php
languages
includes
admin
js
css
images
plublic
js
css
images
Mejores Prácticas
Condicionales de carga
if( is_admin() ) {
// Mostrar ajustes de
// administración
}
Roles
Super Admin Editor
create_sites delete_others_pages
delete_sites delete_others_posts
manage_network delete_pages
manage_sites delete_posts
manage_network_users delete_private_pages
manage_network_plugins delete_private_posts
manage_network_themes delete_published_pages
manage_network_options delete_published_posts
edit_others_pages
Administrator edit_others_posts
activate_plugins edit_pages
delete_others_pages edit_posts
delete_others_posts edit_private_pages
delete_pages edit_private_posts
delete_posts edit_published_pages
delete_private_pages edit_published_posts
delete_private_posts manage_categories
delete_published_pages manage_links
delete_published_posts moderate_comments
edit_dashboard publish_pages
edit_others_pages publish_posts
edit_others_posts read
edit_pages read_private_pages
edit_posts read_private_posts
edit_private_pages unfiltered_html
edit_private_posts upload_files
edit_published_pages
edit_published_posts Author
edit_theme_options
export delete_posts
import delete_published_posts
list_users edit_posts
manage_categories edit_published_posts
manage_links publish_posts
manage_options read
moderate_comments upload_files
promote_users
publish_pages Contributor
publish_posts
read_private_pages delete_posts
read_private_posts edit_posts
read read
remove_users
switch_themes Subscriber
upload_files
read
customize
delete_site
update_core
update_plugins
update_themes
install_plugins
install_themes
upload_plugins
upload_themes
delete_themes
delete_plugins
edit_plugins
edit_themes
edit_files
edit_users
create_users
delete_users
unfiltered_html
Capability Super Admin Administrator Editor Author Contributor Subscriber
create_sites Y
delete_sites Y
manage_network Y
manage_sites Y
manage_network_users Y
manage_network_plugins Y
manage_network_themes Y
manage_network_options Y
upload_plugins Y
upload_themes Y
activate_plugins Y Y
(single site or
enabled by network setting)
edit_theme_options Y Y
export Y Y
import Y Y
list_users Y Y
manage_options Y Y
promote_users Y Y
remove_users Y Y
switch_themes Y Y
edit_dashboard Y Y
customize Y Y
delete_site Y Y
moderate_comments Y Y Y
manage_categories Y Y Y
manage_links Y Y Y
edit_others_posts Y Y Y
edit_pages Y Y Y
edit_others_pages Y Y Y
edit_published_pages Y Y Y
publish_pages Y Y Y
delete_pages Y Y Y
delete_others_pages Y Y Y
delete_published_pages Y Y Y
delete_others_posts Y Y Y
delete_private_posts Y Y Y
edit_private_posts Y Y Y
read_private_posts Y Y Y
delete_private_pages Y Y Y
edit_private_pages Y Y Y
read_private_pages Y Y Y
edit_published_posts Y Y Y Y
upload_files Y Y Y Y
publish_posts Y Y Y Y
delete_published_posts Y Y Y Y
edit_posts Y Y Y Y Y
delete_posts Y Y Y Y Y
read Y Y Y Y Y Y
Validación de datos
Funciones integradas de PHP
isset() - empty()
mb_strlen() - strlen()
preg_match, strpos()
count()
in_array()
Validación de datos
Funciones de WordPress
is_email()
term_exists()
username_exists()
validate_file()
*_exists()
*_validate()
is_*()
Asegurando la
entrada de datos
sanitize_*()
sanitize_email()
sanitize_file_name()
sanitize_html_class()
sanitize_key()
sanitize_meta()
sanitize_mime_type()
sanitize_option()
sanitize_sql_orderby()
sanitize_text_field()
sanitize_title()
sanitize_title_for_query()
sanitize_title_with_dashes()
sanitize_user()
esc_url_raw()
wp_filter_post_kses()
wp_filter_nohtml_kses()
Asegurando la
salida de datos
Escapando
esc_html()
esc_url()
esc_js()
esc_attr()
Escapadas personalizadas
wp_kses()
NONCES
wp_create_nonce()
wp_verify_nonce()
Menús
Agregando menú
add_menu_page(
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
callable $function = '',
string $icon_url = '',
int $position = null
)
add_action( ‘admin_menu’, ‘function_name’ )
Menús
Removiendo menú
remove_menu_page(
string $menu_slug
)
Submenús
Agregando Submenús
add_submenu_page(
string $parent_slug,
string $page_title,
string $menu_title,
string $capability,
string $menu_slug,
callable $function = ''
)
add_action(
string $tag,
callable $function,
int $priority = 10,
int $accepted_args = 1
)
Filtros
add_filter(
string $tag,
callable $function,
int $priority = 10,
int $accepted_args = 1
)
Ganchos personalizados
Creando un gancho de acción
do_action(
string $tag,
$arg = ‘’
)
Creando un gancho de filtro
apply_filters(
string $tag,
mixed $value,
$arg = ‘’
)
Ganchos personalizados
Eliminando una función Callback de un gancho
remove_action(
string $tag,
callback $function_to_remove,
int $priority = 10,
)
Eliminando todas las funciones Callback de un gancho
remove_all_actions(
string $tag,
int|bool $priority = false
)
Determinando el
Gancho Actual
Current_action()
Current_filter()
Comprobando la cantidad
de ejecución
function mp_depurando()
{
echo ‘<p>’.current_action().‘</p>’;
}
add_action(‘all’, ‘mp_depurando’);
Capacidades de Usuario
create_sites Y
delete_sites Y
manage_network Y
manage_sites Y
manage_network_users Y
manage_network_plugins Y
manage_network_themes Y
manage_network_options Y
upload_plugins Y
upload_themes Y
activate_plugins Y Y
(single site or
enabled by network setting)
edit_theme_options Y Y
export Y Y
import Y Y
list_users Y Y
manage_options Y Y
promote_users Y Y
remove_users Y Y
switch_themes Y Y
edit_dashboard Y Y
customize Y Y
delete_site Y Y
moderate_comments Y Y Y
manage_categories Y Y Y
manage_links Y Y Y
edit_others_posts Y Y Y
edit_pages Y Y Y
edit_others_pages Y Y Y
edit_published_pages Y Y Y
publish_pages Y Y Y
delete_pages Y Y Y
delete_others_pages Y Y Y
delete_published_pages Y Y Y
delete_others_posts Y Y Y
delete_private_posts Y Y Y
edit_private_posts Y Y Y
read_private_posts Y Y Y
delete_private_pages Y Y Y
edit_private_pages Y Y Y
read_private_pages Y Y Y
edit_published_posts Y Y Y Y
upload_files Y Y Y Y
publish_posts Y Y Y Y
delete_published_posts Y Y Y Y
edit_posts Y Y Y Y Y
delete_posts Y Y Y Y Y
read Y Y Y Y Y Y
Settings API
register_setting(
string $option_group,
string $option_name,
string|array $callbakc|$args
);
$sanitize_callback = ‘func_name’;
$args = [
'type' => 'string',
'group' => $option_group,
'description' => '',
'sanitize_callback' => null,
'show_in_rest' => false,
];
Settings API
add_settings_section(
string $id,
string $title,
callable $callback,
string $page
);
Settings API
add_settings_field(
string $id,
string $title,
callable $callback,
string $page,
string $section,
array $args = []
);
Settings API
register_setting() register_setting()
unregister_setting() unregister_setting()
settings_fields() add_settings_error()
do_settings_sections() get_settings_errors()
do_settings_fields() settings_errors()
Settings API
register_setting(
string $option_group,
string $option_name,
string|array $callbakc|$args
);
$sanitize_callback = ‘func_name’;
$args = [
'type' => 'string',
'description' => '',
'sanitize_callback' => null,
'show_in_rest' => false,
'default' => $array()
];
Settings API
add_settings_section(
string $id,
string $title,
callable $callback,
string $page
);
Settings API
add_settings_field(
string $id,
string $title,
callable $callback,
string $page,
callable $section,
array $args = []
);
Options API
add_option(
string $option,
mixed $value = ‘’,
string $deprecated = ‘’,
string|bool $autoload = ‘yes’
);
Options API
get_option(
string $option,
mixed $default = false
);
Options API
update_option(
string $option,
mixed $value,
string|bool $autoload = null
);
Options API
delete_option(
string $option
);
Página de configuración
personalizada
Menú de administración
API Settings
API Options
Página de configuración
personalizada
register_setting() add_settings_section()
unregister_setting() add_settings_field()
settings_fields() add_settings_error()
do_settings_sections() get_settings_errors()
do_settings_fields() settings_errors()
Página de configuración
personalizada
add_settings_error(
string $setting,
string $code,
callable $message,
string $type = ‘error’
);
settings_errors(
string $setting,
bool $sanitize = false,
bool $hide_on_update = false
);
post revision
page menu
attachment
Custom Post Type
register_post_type(
string $post_type,
array|string $args = array()
);
Custom Post Type
Propias URL
http://misitio.com/productos/%titulo_producto%
http://misitio.com/productos/manzana
Archivos personalizados para los CPT
single-{post-type}.php
single-productos.php
archive-{post-type}.php
archive-productos.php
Loop, WP_Query
$query->have_posts(); $query->the_post();
Funciones iniciales
Muestra el título
the_title(); get_the_title();
Muestra el contenido
the_content(); get_the_content();
the_post_thumbnail() get_the_post_thumbnail();
the_permalink() get_the_permalink();
the_author(); get_the_author();
the_date() get_the_date();
Muestra el ID de la publicación
the_ID(); $post->ID;
Metadatos
Agrega un metadato
add_post_meta(
int $post_id,
string $meta_key,
mixed $meta_value,
bool $unique = false
);
Actualiza un metadato
update_post_meta(
int $post_id,
string $meta_key,
mixed $meta_value,
mixed $prev_value = ‘’
);
Metadatos
Borrar un metadato
delete_post_meta(
int $post_id,
string $meta_key,
mixed $meta_value
);
Obtener un metadato
get_post_meta(
int $post_id,
string $meta_key = ‘’,
bool $single = false
);
MetaBoxes
add_meta_box(
string $id,
string $title,
callable $callback,
string|array|WP_Screen $screen = null,
string $context = ‘advanced’,
string $priority = ‘default’,
array $callback_args = null
);
MetaBoxes
remove_meta_box(
string $id,
string|array|WP_Screen $screen,
string $context
);
WP_EDITOR - TinyMCE (WYSIWYG)
wp_editor(
string $content,
string $editor_id,
array $settings = array()
);
Encolamiento (Enqueue)
‘wp_enqueue_scripts’
‘admin_enqueue_scripts’
‘login_enqueue_scripts’
Encolamiento (Enqueue)
Funciones de encolamiento
wp_enqueue_style();
wp_enqueue_script();
Encolamiento (Enqueue)
wp_enqueue_style(
string $handle,
string $src = ‘’,
array $deps = array(),
string|bool|null $ver = false,
string $media = ‘all’,
);
Encolamiento (Enqueue)
wp_enqueue_script(
string $handle,
string $src = ‘’,
array $deps = array(),
string|bool|null $ver = false,
bool $in_footer = false,
);
Registro
Funciones de registro
wp_register_style();
wp_register_script();
Registro
wp_register_style(
string $handle,
string $src = ‘’,
array $deps = array(),
string|bool|null $ver = false,
string $media = ‘all’,
);
Registro
wp_register_script(
string $handle,
string $src = ‘’,
array $deps = array(),
string|bool|null $ver = false,
bool $in_footer = false,
);
Dequeue | Deregister
wp_dequeue_style();
wp_dequeue_script();
wp_deregister_style();
wp_deregister_script();
Taxonomías
Taxonomía
Marcas
Volskwagen Audi
Renault
register_taxonomy(
string $name_taxonomy,
array|string $post_type,
array|string $args array()
);
the_terms()
get_the_term_list()
wp_tag_cloud()
get_terms()
Metadatos de los términos
add_term_meta()
get_term_meta()
update_term_meta()
delete_term_meta()
Usuarios
Usuarios
Agregar un usuario
wp_create_user();
wp_insert_user();
Usuarios
Agregar un usuario
wp_create_user(
string $username,
string $password,
string $email = ‘error’
);
Funciones de ayuda
username_exists();
email_exists();
wp_generate_password();
Usuarios
Agregar un usuario
wp_insert_user(
array|object|WP_User $userdata
);
Usuarios
Eliminando usuarios
add_user_meta()
get_user_meta()
update_user_meta()
delete_user_meta()
Funciones básicas
wp_roles()
WP_User->roles
Métodos del Objeto WP_User para la manipulación de los Roles en los usuarios
Métodos del Objeto WP_Roles para la manipulación de las capacidades del un rol
Métodos del Objeto WP_Roles para la manipulación de las capacidades del un rol
WP_User->allcaps
Usuarios
WP_Roles::get_names()
WP_Roles->role_names
WP_Roles::is_role( $role )
WP_User::has_prop( $key )
WP_User::exists()
HTTP
http://www.servidor.com/pagina.html
Respuesta
HTTP
Métodos HTTP
Códigos
Descripción
de estado
Códigos Descripción
de estado
Función para realizar cualquier tipo de petición (get, post, head, put, delete, trace, connect)
wp_remote_request( string $url, array $args ) $args = [“method”=>“delete”]
method – GET
timeout – 5 – Cuánto tiempo esperar una conexión inactiva para cerrarla
redirection – 5 – Cuántas veces seguir las redirecciones.
httpversion – 1.0
blocking – true – ¿Debería esperar el resto de la página para terminar de cargar
hasta que esta operación esté completa?
headers – array()
body – null
cookies – array()
Peticiones HTTP
wp_localize_script(
string $handle,
string $object_name,
array $l10n
)
Verifica la solicitud de AJAX para evitar procesar solicitudes externas al sitio web.
check_ajax_referer(
int|string $action = -1,
false|string $query_arg = false,
bool $die = true
)
Heartbeat API
Encola los datos a un manejador (handle) y los envia usando el método AJAX en Javascript
Configuraciones
Filtro para cambiar algunas configuraciones del Heartbeat
add_filter( ‘heartbeat_settings’, ‘function_name’, 10, 1 )
@param ( array $settings )
$settings[‘ajaxurl’] = admin_url(‘admin-ajax.php’)
$settings[‘minimalInterval’] = 15
$settings[‘interval’] = 15-120
$settings[‘suspension’] = ‘disabled’
Contraseña
Recordar
Contraseña
INICIAR SESIÓN
Recordar
INICIAR SESIÓN
WIDGETS
Construye los atributos de id para su uso en los campos del método form()
$this->get_field_id( string $field_name );
Construye los atributos name para su uso en los campos del método form()
$this->get_field_name( string $field_name );
WP CRON
Tiempo UNIX
1501300291
Hora y fecha: [ 22 : 51 : 31 ] 28 / 07 / 2017 (+0500)
ISO 8601: 2017-07-28T22:51:31+05:00
RFC 2822: Fri, 28 Jul 2017 22:51:31 +0500
WP CRON
Intervalos predeterminados
Función que permite programar un evento que se ejecute una sola vez
wp_schedule_single_event(
ing $timestamp,
string $hook,
array $args = array()
)
¿Qué es la
Internacionalización?
INTERNACIONALIZACIÓN
i18n
1 18
Internationalization
INTERNACIONALIZACIÓN
¿Qué es la
Localización?
Abreviatura
l10n
1 10
Localization
Archivos de Localización
1 #: ruta1/archivo.php:12 ruta2/archivo.php:17
2 msgid "User Social"
3 msgstr " "
POT
Archivos de Localización
1 #: includes/mp-menu.php:150
2 msgid "User Social"
3 msgstr "Usuarios Social"
PO
Archivos de Localización
01001101 01101001
10011011 10100111
01001010 11010011
MO
Archivos de Localización
Procesos
Traducción Compilación Binaria
ES ES Español
PO MO
EN EN Inglés
POT PO MO
FR FR Francés
PO MO
Funciones de traducción
Funciones Básicas
printf(
__( 'Mi ciudad es %s.', 'mitextdomain' ),
$city
);
sprintf(
__( 'Mi ciudad es %s.', 'mitextdomain' ),
$city
);
Pluralización Básica
1 mensaje
5 mensajes
Pluralización Básica
_n(
str $singular,
str $plural,
int $number,
str $domain
)
Pluralización
_n_noop()
_nx_noop()
translate_nooped_plural()
Desambiguación por contexto
Post link
Desambiguación por contexto
Un enlace a la publicación
o
Enviar un enlace
Desambiguación por contexto
_x()
_ex()
_nx()
_nx_noop()
Instancia Objeto Global $wpdb
class wpdb {
// ...
}
Instancia Objeto Global $wpdb
Consulta de variable, fila y columna específica
$wpdb->get_var( str $query, int column_offset, int row_offset )
$wpdb->get_row( str $query, int output_type, int row_offset )
$wpdb->get_col( str $query, int column_offse )
Consultas predefinidas
Consultas generales
$wpdb->query( str $query )
$wpdb->show_errors()
$wpdb->hide_errors()
Propiedades
$wpdb->insert_id
$wpdb->show_errors
$wpdb->num_queries
$wpdb->last_query
$wpdb->last_error
$wpdb->queries
$wpdb->last_result
$wpdb->col_info
$wpdb->insert_id
$wpdb->num_rows
$wpdb->prefix
$wpdb->base_prefix
Multisitio
$wpdb->blogid
$wpdb->siteid
Instancia Objeto Global $wpdb
$posts
$postmeta
$comments
$commentmeta
$termmeta
$terms
$term_taxonomy
$term_relationships
$users
$usermeta
$links
$options
Instancia Objeto Global $wpdb
$wpdb
Instancia Objeto Global $wpdb
global $wpdb
$GLOBALS['wpdb']
Métodos $wpdb
Columnas
0 1 2 3
id nombre apellido teléfono
Filas
Consultas predefinidas
Consultas generales
$wpdb->query( str $query )
Métodos
Propiedades
$wpdb->insert_id
$wpdb->show_errors
$wpdb->num_queries
$wpdb->last_query
$wpdb->last_error
$wpdb->queries
$wpdb->last_result
$wpdb->col_info
$wpdb->insert_id
$wpdb->num_rows
$wpdb->prefix
$wpdb->base_prefix
Multisitio
$wpdb->blogid
$wpdb->siteid
Marcos de Gestión Multimedia
¿Qué es Backbone?
Marcos de Gestión Multimedia
Encola todos los archivos necesarios para poder utilizar el objeto wp.media
wp_enqueue_media()