<?php
/*
Plugin Name: Plugin propio
Plugin URI: http://intelisen.com/plugins
Description: Un plugin para probar cosas
Author: Intelisen
Version: 1
Author URI: http://intelisen.com
*/
add_filter('the_content', 'cambiar_contenido');
function cambiar_contenido($contenido) {
return $contenido . " ¡Mega artículo!";
}
add_filter('the_title', 'cambia_titulo');
function cambia_titulo($contenido) {
return "###==>" . $contenido;
}
add_action('admin_notices', 'saludo');
function saludo() {
echo "ola k ase???";
}
add_action('wp_head', 'ponjquery');
function ponjquery() {
echo '<El código que pongamos aquí se pintará en la cabecera (head) del wordpress>'
. '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>';
}
function google_shortcode() {
return '<input onclick="location.href=\'http://google.es\'" type="button" value="Ir a google" />';
}
add_shortcode('google_atajo', 'google_shortcode');
function refran() {
$refranes = ["No por mucho madrugar amanece más temprano", "A quien madruga dios le ayuda", "Más vale pájaro en mano que ciento volando"];
return "<p>" . $refranes[rand(0, count($refranes) - 1)] . "</p>";
}
add_shortcode('refran', 'refran');
function imagenes() {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'posts_per_page' => - 1,
);
$query_images = new WP_Query($query_images_args);
$imagen = $query_images->posts[rand(0, count($query_images->posts) - 1)];
return '<img width=300 height=300 src="' . $imagen->guid . '"/>';
}
add_shortcode('imagenes', 'imagenes');
//Necesarios para crear un menú y registrar los campos
add_action('admin_menu', 'destacar_menu');
add_action('admin_init', 'destacar_settings');
//Registra el campo que vamos a guardar
function destacar_settings() {
register_setting('destacar-group', 'destacar_palabras');
register_setting('destacar-group', 'destacar_color');
}
//Son las opciones que tendrá nuestro menú. Los parámetros son: título de la página, título del menú, quien puede acceder, url de esta página y función a la que se llama
function destacar_menu() {
add_options_page('Opciones destacar', 'Destacar', 'manage_options', 'destacar-identifier', 'destacar_options');
}
//Formulario que se mostrará cuando se seleccione el menú
function destacar_options() {
if (!current_user_can('manage_options')) {
wp_die('No tiene permiso.');
}
?>
<div>
<?php screen_icon(); ?>
<h2>Opciones destacar</h2>
<form method="post" action="options.php">
<?php
settings_fields('destacar-group');
do_settings_fields('destacar-group', '');
?>
<p>Introduzca las palabras a destacar separadas por comas</p>
<input size="70" type="text" name="destacar_palabras" value="<?php echo get_option('destacar_palabras'); ?>" />
<p>Introduzca el color que quiere usar para destacar</p>
<input size="70" type="text" name="destacar_color" value="<?php echo get_option('destacar_color'); ?>" />
<?php
submit_button();
?>
</form>
</div>
<?php
}
//Las dos funciones siguientes y el add_filter son el código del plugin
function destacar_get_palabras() {
return explode(",", get_option("destacar_palabras"));
}
function destacar_filtro($contenido) {
$palabras = destacar_get_palabras();
foreach ($palabras as $palabra) {
$palabra = trim($palabra);
$contenido = str_ireplace($palabra, "<span style='background-color:" . get_option("destacar_color") . "'>" . $palabra . "</span>", $contenido);
}
return $contenido;
}
add_filter('the_content', 'destacar_filtro');
class EntradasWidget extends WP_Widget {
function EntradasWidget() {
$widget_ops = array('classname' => 'EntradasWidget', 'description' => 'Muestra entrada aleatoria');
$this->WP_Widget('EntradasWidget', 'Entrada aleatoria con thumbnail', $widget_ops);
}
function form($instance) {
$instance = wp_parse_args((array) $instance, array('title' => ''));
$title = $instance['title'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>"><?= _e('Title') ?>: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
return $instance;
}
function widget($args, $instance) {
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
// CóDIGO DEL WIDGET
$posts = get_posts('orderby=rand;numberposts=1');
$post = $posts[0];
?><a href="<?= get_permalink($post); ?>" title="<?= $post->post_title; ?>"><?= $post->post_title; ?></a>
<?php
echo $after_widget;
}
}
add_action('widgets_init', create_function('', 'return register_widget("EntradasWidget");'));
Autor: Juan Pablo Fuentes
Formador de programación y bases de datos
Ejemplos shortcodes
Pone un refrán aleatorio:
function refran() {
$refranes = ["No por mucho madrugar amanece más temprano", "A quien madruga dios le ayuda", "Más vale pájaro en mano que ciento volando"];
return "<p>" . $refranes[rand(0, count($refranes) - 1)] . "</p>";
}
add_shortcode('refran', 'refran');
Pone una imagen aleatoria de la biblioteca de medios:
function imagenes() {
$query_images_args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'posts_per_page' => - 1,
);
$query_images = new WP_Query($query_images_args);
$imagen = $query_images->posts[rand(0, count($query_images->posts) - 1)];
return '<img width=300 height=300 src="' . $imagen->guid . '"/>';
}
add_shortcode('imagenes', 'imagenes');
Plantillas de curriculum gratuitas
30 temas para usar woocommerce
sakila.php
<?php
class Sakila {
private $server = "localhost";
private $user = "root";
private $password = "";
private $db = "sakila";
public $conn;
function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
function pepe(){
return 3;
}
function getActors() {
$sql = "select * from actor where 1=1";
$query = $this->conn->query($sql);
return $query->fetchAll();
}
function getActor($id) {
$sql = "select * from actor where actor_id=$id";
$query = $this->conn->query($sql);
return $query->fetch();
}
/**
*
* @param type $actor array asociativo con los campos del actor
* ejemplo: ['actor_id'=>1,'first_name'=>'Santiago','last_name'=>'Segura']
*/
function updateActor($actor) {
$sql = "update actor set first_name='" . $actor['first_name'] . "', last_name='" . $actor['last_name'] . "'
where actor_id=" . $actor['actor_id'] . ";";
$this->conn->exec($sql);
}
function deleteActor($id) {
$sql = "delete from actor where actor_id=$id";
$this->conn->exec($sql);
}
/**
* Inserta un nuevo actor o devuelve el id si ya existe
* @param string valor de first_name
* @param string valor de last_name
* @return int id
*/
function newActor($first_name, $last_name) {
if (!empty($first_name) && !empty($last_name)) {
$sql = "select * from actor where first_name=:first_name and last_name=:last_name";
$st = $this->conn->prepare($sql);
$st->execute([':first_name' => $first_name, ':last_name' => $last_name]);
if ($actor = $st->fetch()) {
return $actor['actor_id'];
}
$sql = "insert into actor (first_name,last_name) values (:first_name,:last_name)";
$st = $this->conn->prepare($sql);
$st->execute([':first_name' => $first_name, ':last_name' => $last_name]);
return $this->conn->lastInsertId();
} else {
return null;
}
}
/**
* Inserta una película en una categoría
* @param int id de la categoría
* @param string título de la película
*/
function newFilm($category_id, $film) {
$this->conn->beginTransaction();
try {
$sql = "insert into film(title,language_id) values (:film,1)";
$st = $this->conn->prepare($sql);
$st->execute([':film' => $film]);
$film_id = $this->conn->lastInsertId();
$sql = "insert into film_category(film_id,category_id) values($film_id,$category_id)";
$this->conn->exec($sql);
$this->conn->commit();
} catch (PDOException $e) {
echo $e->getMessage();
$this->conn->rollBack();
}
}
/**
* Crea un select con todas las categorías
*/
function selectCategory() {
$sql = "select * from category";
$q = $this->conn->query($sql);
$categorias = $q->fetchAll();
?>
<select name="category">
<?php foreach ($categorias as $categoria) {
?>
<option value="<?= $categoria['category_id'] ?>"><?= $categoria['name'] ?></option>
<?php } ?>
</select>
<?php
}
}
Teoría vs práctica
Mantenimento actores
sakila.php
<?php
class Sakila {
private $server = "localhost";
private $user = "root";
private $password = "";
private $db = "sakila";
public $conn;
function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
function getActors() {
$sql = "select * from actor";
$query = $this->conn->query($sql);
return $query->fetchAll();
}
function getActor($id) {
$sql = "select * from actor where actor_id=$id";
$query = $this->conn->query($sql);
return $query->fetch();
}
/**
*
* @param type $actor array asociativo con los campos del actor
* ejemplo: ['actor_id'=>1,'first_name'=>'Santiago','last_name'=>'Segura']
*/
function updateActor($actor) {
$sql = "update actor set first_name='" . $actor['first_name'] . "', last_name='" . $actor['last_name'] . "'
where actor_id=" . $actor['actor_id'] . ";";
$this->conn->exec($sql);
}
function deleteActor($id) {
$sql = "delete from actor where actor_id=$id";
$this->conn->exec($sql);
}
/**
* Inserta un nuevo actor o devuelve el id si ya existe
* @param string valor de first_name
* @param string valor de last_name
* @return int id
*/
function newActor($first_name, $last_name) {
if (!empty($first_name) && !empty($last_name)) {
$sql = "select * from actor where first_name=:first_name and last_name=:last_name";
$st = $this->conn->prepare($sql);
$st->execute([':first_name' => $first_name, ':last_name' => $last_name]);
if ($actor = $st->fetch()) {
return $actor['actor_id'];
}
$sql = "insert into actor (first_name,last_name) values (:first_name,:last_name)";
$st = $this->conn->prepare($sql);
$st->execute([':first_name' => $first_name, ':last_name' => $last_name]);
return $this->conn->lastInsertId();
} else {
return null;
}
}
/**
* Inserta una película en una categoría
* @param int id de la categoría
* @param string título de la película
*/
function newFilm($category_id, $film) {
$this->conn->beginTransaction();
try {
$sql = "insert into film(title,language_id) values (:film,1)";
$st = $this->conn->prepare($sql);
$st->execute([':film' => $film]);
$film_id = $this->conn->lastInsertId();
$sql = "insert into film_category(film_id,category_id) values($film_id,$category_id)";
$this->conn->exec($sql);
$this->conn->commit();
} catch (PDOException $e) {
echo $e->getMessage();
$this->conn->rollBack();
}
}
/**
* Crea un select con todas las categorías
*/
function selectCategory() {
$sql = "select * from category";
$q = $this->conn->query($sql);
$categorias = $q->fetchAll();
?>
<select name="category">
<?php foreach ($categorias as $categoria) {
?>
<option value="<?= $categoria['category_id'] ?>"><?= $categoria['name'] ?></option>
<?php } ?>
</select>
<?php
}
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
</head>
<body>
<div class="container">
<?php
include "sakila.php";
$sakila = new Sakila();
$nuevo = filter_input(INPUT_GET, 'nuevo');
$first_name = filter_input(INPUT_GET, 'first_name');
$last_name = filter_input(INPUT_GET, 'last_name');
if (!empty($nuevo) && !empty($first_name) && !empty($last_name)) {
$sakila->newActor($first_name, $last_name);
}
$cambiar = filter_input(INPUT_GET, 'cambiar');
$actor_id = filter_input(INPUT_GET, 'actor_id');
if (!empty($cambiar) && !empty($actor_id) && !empty($first_name) && !empty($last_name)) {
$sakila->updateActor(['actor_id' => $actor_id, 'first_name' => $first_name, 'last_name' => $last_name]);
}
$delete = filter_input(INPUT_POST, 'delete');
$actor_id = filter_input(INPUT_POST, 'actor_id');
if (!empty($delete) && !empty($actor_id)) {
$sakila->deleteActor($actor_id);
}
$actores = $sakila->getActors();
?>
<h1>Mantenimiento actores</h1>
<form>
<div class="form-group">
<label for="first_name">Nombre:</label>
<input type="text" class="form-control" name="first_name">
</div>
<div class="form-group">
<label for="last_name">Apellidos:</label>
<input type="text" class="form-control" name="last_name">
</div>
<input class="btn btn-success" type="submit" name="nuevo" value="Nuevo">
</form>
<table class="table">
<tr><td>Nombre</td><td>Apellidos</td><td>Acciones</td></tr>
<?php
foreach ($actores as $actor) {
?>
<tr><td><?= $actor['first_name'] ?></td><td><?= $actor['last_name'] ?></td>
<td><a href="editar.php?actor_id=<?= $actor['actor_id'] ?>" class="btn btn-success">Editar</a>
<form action="index.php" method="post" style="float:left;margin-right: 10px">
<input type="hidden" name="actor_id" value="<?= $actor['actor_id'] ?>">
<input class="btn btn-success" type="submit" name="delete" value="Borrar">
</form>
</td></tr>
<?php
}
?>
</table>
</div>
</body>
</html>
editar.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
</head>
<body>
<div class="container">
<?php
include "sakila.php";
$sakila = new Sakila();
$actor_id = filter_input(INPUT_GET, 'actor_id');
if (!empty($actor_id)) {
$actor = $sakila->getActor($actor_id);
}
?>
<h1>Editar actor</h1>
<form action="index.php">
<input type="hidden" class="form-control" name="actor_id" value="<?= $actor['actor_id'] ?>">
<div class="form-group">
<label for="first_name">Nombre:</label>
<input type="text" class="form-control" name="first_name" value="<?= $actor['first_name'] ?>">
</div>
<div class="form-group">
<label for="last_name">Apellidos:</label>
<input type="text" class="form-control" name="last_name" value="<?= $actor['last_name'] ?>">
</div>
<input class="btn btn-success" type="submit" name="cambiar" value="Cambiar">
</form>
</div>
</body>
</html>
Instalar composer
Qué es composer:
https://styde.net/que-es-composer-y-como-usarlo/
Página oficial:
Instrucciones paso a paso:
Clase sakila
<?php
class Sakila {
private $server = "localhost";
private $user = "root";
private $password = "";
private $db = "sakila";
private $conn;
function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
/**
* Inserta un nuevo actor o devuelve el id si ya existe
* @param string valor de first_name
* @param string valor de last_name
* @return int id
*/
function newActor($first_name, $last_name) {
if (!empty($first_name) && !empty($last_name)) {
$sql = "select * from actor where first_name='$first_name' and last_name='$last_name'";
$c = $this->conn->query($sql);
if ($actor = $c->fetch()) {
return $actor['actor_id'];
}
$sql = "insert into actor (first_name,last_name) values ('$first_name','$last_name')";
$this->conn->exec($sql);
return $this->conn->lastInsertId();
} else {
return null;
}
}
/**
* Inserta una película en una categoría
* @param int id de la categoría
* @param string título de la película
*/
function newFilm($category_id, $film) {
$sql = "insert into film(title,language_id) values ('$film',1)";
$this->conn->exec($sql);
$film_id = $this->conn->lastInsertId();
$sql = "insert into film_category(film_id,category_id) values($film_id,$category_id)";
$this->conn->exec($sql);
}
/**
* Crea un select con todas las categorías
*/
function selectCategory() {
$sql = "select * from category";
$q = $this->conn->query($sql);
$categorias = $q->fetchAll();
?>
<select name="category">
<?php foreach ($categorias as $categoria) {
?>
<option value="<?= $categoria['category_id'] ?>"><?= $categoria['name'] ?></option>
<?php } ?>
</select>
<?php
}
}
Añadir película y categoría con clases
sakila.php
<?php
class Sakila {
private $server = "localhost";
private $user = "root";
private $password = "";
private $db = "sakila";
private $conn;
function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->user, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
function newFilm($category_id, $film) {
$sql = "insert into film(title,language_id) values ('$film',1)";
$this->conn->exec($sql);
$film_id = $this->conn->lastInsertId();
$sql = "insert into film_category(film_id,category_id) values($film_id,$category_id)";
$this->conn->exec($sql);
}
function selectCategory() {
$sql = "select * from category";
$q = $this->conn->query($sql);
$categorias = $q->fetchAll();
?>
<select name="category">
<?php foreach ($categorias as $categoria) {
?>
<option value="<?= $categoria['category_id'] ?>"><?= $categoria['name'] ?></option>
<?php } ?>
</select>
<?php
}
}
index.php
<?php
include "sakila.php";
$sakila = new Sakila();
$category = filter_input(INPUT_GET, "category", FILTER_VALIDATE_INT);
$film = filter_input(INPUT_GET, "film");
if (!empty($category) && !empty($film)) {
$sakila->newFilm($category, $film);
}
?>
<form>
Categoría:
<?php $sakila->selectCategory(); ?>
<br/>
Película: <input type="text" name="film"><br/>
<input type="submit">
</form>
