<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>emenia.es &#187; PHP</title>
	<atom:link href="http://www.emenia.es/category/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.emenia.es</link>
	<description>Creación y diseño web</description>
	<lastBuildDate>Mon, 31 May 2010 14:34:56 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Filtrar el spam de un formulario con Akismet</title>
		<link>http://www.emenia.es/formulario-filtrar-spam-akismet/</link>
		<comments>http://www.emenia.es/formulario-filtrar-spam-akismet/#comments</comments>
		<pubDate>Sun, 11 Apr 2010 10:40:18 +0000</pubDate>
		<dc:creator>Juan Diaz-Bustamante</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.emenia.es/?p=842</guid>
		<description><![CDATA[Wordpress incorpora un servicio para filtrar el Spam de los comentarios llamado Akismet. Podemos utilizar también Akismet fuera de Wordpress ya que está disponible para gran cantidad de CMS, lenguajes y frameworks. Vamos a ver su uso para PHP 5.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.emenia.es%2Fformulario-filtrar-spam-akismet%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.emenia.es%2Fformulario-filtrar-spam-akismet%2F&amp;source=JuanDBB_Emenia&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Los que hayáis creado webs o blogs con Wordpress sabéis ya que incorpora un potente servicio  llamado <a href="http://akismet.com/" title="Ir a la web de Akismet">Akismet</a> para verificar, filtrar y reportar si un mensaje es considerado Spam. Aunque sus comienzos proceden de Wordpress existen ya <a href="http://akismet.com/development/" title="ver plugins">gran cantidad de plugins</a> para otros CMS (Drupal, Joomla, Expression Engine&#8230;), lenguajes y frameworks (PHP, Ruby, Phyton, Java, Ruby on Rails, Coldfusion, Codeigniter&#8230;.). </p>
<p>Vamos a centrarnos en el <a href="http://www.achingbrain.net/stuff/php/akismet" title="Web oficical del plugin de Akismet para PHP5">plugin para PHP 5</a>.</p>
<p>Lo primero que tenemos que hacer es descargarnos Akismet:<br />
<a href="http://www.achingbrain.net/files/PHP5Akismet/PHP5Akismet.0.4.zip"  title="Descargar Akismet para PHP5">PHP5Akismet.0.4.zip</a> 24K</p>
<p>A continuación descomprimimos el archivo <em>Akismet.class.php</em> y lo archivamos en una carpeta de nuestro proyecto (a efectos de este ejemplo suponemos que lo guardamos en la carpeta <em>&#8220;includes&#8221;</em>)</p>
<p>Ahora ya estamos listos para usarlo. Hay que tener en cuenta que en nuestro formulario deberíamos tener además un sistema de validación (tanto en Javascript como en PHP) adicionales. Una vez que el formulario enviado pase dichos filtros estaríamos en condiciones de establecer un filtro más, el de Akismet:</p>
<h3>Primer paso: obtener la clave (API key)</h3>
<p>Para usar Akismet necesitamos antes de nada obtener una clave (API key) para activar y usar Akismet. Esta clave es gratuita y la podemos obtener <a href="http://akismet.com/personal/" title="Obtener clave Akismet">desde la misma página de Akismet</a>. Debéis tener en cuenta que hay ciertas condiciones de uso para las cuales necesitaríais obtener una clave comercial.</p>
<p>En el formulario se nos pide una dirección de correo electrónico, la enviamos y recibiremos la clave.</p>
<h3>Segundo paso: Incluir Akismet en nuestro código</h3>
<p>Una vez tengamos la clave ya podemos incluir Akismet. Como vimos más arriban tenemos el archivo <em>Akismet.class.php</em> dentro de la carpeta <em>&#8220;includes&#8221;</em>. Para incluirlo hacemos símplemente:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Incluimos la clase Akismet</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'includes/Akismet.class.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Incluir la clave (API key)</h3>
<p>El siguiente paso es incluir la clave que nos ha proporcionado Akismet así como la URL de nuestra web</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Introducirmos la API key para nuestra web</span>
<span style="color: #000088;">$api_key</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'aqui va la clave'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$blog_url</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://www.miweb.com&quot;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Creamos el objeto Akismet</h3>
<p>A continuación creamos el objeto Akismet:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Creamos el objeto Akismet</span>
<span style="color: #000088;">$akismet</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Akismet<span style="color: #009900;">&#40;</span><span style="color: #000088;">$blog_url</span> <span style="color: #339933;">,</span><span style="color: #000088;">$api_key</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Probamos si la clave (API key) es válida</h3>
<p>Estas líneas sólo nos serviran para comprobar si la clave que tenemos es válida. Una vez veamos que todo va bien las podemos eliminar. O también podemos incluir todo el código que crearemos a continuación dentro del condicional, para que sólo se ejecute si la clave es válida.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isKeyValid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'&lt;p&gt;La clave es buena&lt;/p&gt;'</span><span style="color: #339933;">;</span><span style="color: #666666; font-style: italic;">// api key es buena</span>
<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span> 
<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'&lt;p&gt;La clave no vale&lt;/p&gt;'</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// api key no es buena</span>
 <span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<h3>Definir los campos a filtrar</h3>
<p>A continuación establecemos qué campos de nuestro formulario son los que vamos a filtrar contra Spam. En este caso suponemos el nombre, e-mail, el comentario y una url. Las variables proceden del código que deberíamos haber creado previamente para obtener los valores de $_POST enviados por el formulario que una vez validados se asignan a cada variable.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentAuthor</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$nombre</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentAuthorEmail</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$email</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentContent</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$comentarios</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentAuthorURL</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Establecer el enlace permanente donde el formulario es enviado</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Enlace permanente donde el formulario es enviado</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setPermalink</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'http://www.ejemplo.com/una-url/'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h3>Condicional si se considera spam</h3>
<p>Para saber si Akismet considera que es Spam podemos hacer:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isCommentSpam</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
 <span style="color: #666666; font-style: italic;">// Aquí va el código, mensaje de error o lo que queramos, o incluso archivarlos en algún sitio para comprobarlos más adelante</span>
 <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">// Aquí va el código en el caso de que NO sea Spam</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Y eso es todo, como véis es muy sencillo de usar. Todo el código junto:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Incluimos la clase Akismet</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'includes/Akismet.class.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">//Introducirmos la API key para nuestra web</span>
<span style="color: #000088;">$api_key</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'aqui va la clave'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$blog_url</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;http://www.miweb.com&quot;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Creamos el objeto Akismet</span>
<span style="color: #000088;">$akismet</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Akismet<span style="color: #009900;">&#40;</span><span style="color: #000088;">$blog_url</span> <span style="color: #339933;">,</span><span style="color: #000088;">$api_key</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Condicional para ver si la clave es válida</span>
<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isKeyValid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Campos a filtrar</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentAuthor</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$nombre</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentAuthorEmail</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$email</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentContent</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$comentarios</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setCommentAuthorURL</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Enlace permanente donde el formulario es enviado</span>
<span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setPermalink</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'http://www.ejemplo.com/una-url/'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Decidimos qué hacer si es Spam y si no lo es</span>
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #000088;">$akismet</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isCommentSpam</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
 <span style="color: #666666; font-style: italic;">// Aquí va el código, mensaje de error o lo que queramos, o incluso archivarlos en algún sitio para comprobarlos más adelante.</span>
 <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
<span style="color: #666666; font-style: italic;">// Aquí va el código en el caso de que NO sea Spam, que normalmente será continuar con cualquier proceso de validación o incluso ya con el envío del formulario.</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// Fin del condicional si la clave es válida</span></pre></td></tr></table></div>

<h3>Documentación adicional</h3>
<p><a href="http://akismet.com/" title="Ir a la web de Akismet">Web de Akismet</a><br />
<a href="http://akismet.com/development/api/" title="Documentación de Akismet">Documentación de Akismet</a><br />
Aching Brain, <a href="http://www.achingbrain.net/stuff/php/akismet" title="Ir a Aching Brain">Akismet para PHP5</a></p>
<div id="crp_related"><h3>Artículos relacionados:</h3><ul><li><a href="http://www.emenia.es/primeros-pasos-tras-una-nueva-instalacion-de-wordpress/" rel="bookmark" class="crp_title">Primeros pasos tras una nueva instalación de Wordpress</a></li><li><a href="http://www.emenia.es/utilizando-css3-hoy-1-bordes-redondeados/" rel="bookmark" class="crp_title">Utilizando CSS3 hoy (1): Bordes Redondeados</a></li><li><a href="http://www.emenia.es/curso-de-jquery-3-selectores-segunda-parte/" rel="bookmark" class="crp_title">Curso de jQuery (3): Selectores, Segunda Parte</a></li><li><a href="http://www.emenia.es/como-incrementar-la-seguridad-de-una-web-creada-con-wordpress/" rel="bookmark" class="crp_title">Cómo incrementar la seguridad de una web creada con Wordpress</a></li><li><a href="http://www.emenia.es/calendario-formulario-jquery/" rel="bookmark" class="crp_title">Elegir una fecha en un formulario con un calendario y jQuery</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.emenia.es/formulario-filtrar-spam-akismet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Como utilizar un fondo aleatorio para nuestra web</title>
		<link>http://www.emenia.es/como-utilizar-un-fondo-aleatorio-para-nuestra-web/</link>
		<comments>http://www.emenia.es/como-utilizar-un-fondo-aleatorio-para-nuestra-web/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 07:59:42 +0000</pubDate>
		<dc:creator>Juan Diaz-Bustamante</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://emenia.es/?p=159</guid>
		<description><![CDATA[Hay veces que queremos que el fondo de nuestra web sea distinto cada vez que entramos en la misma. Esto lo podemos hacer de una manera muy sencilla con PHP.]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.emenia.es%2Fcomo-utilizar-un-fondo-aleatorio-para-nuestra-web%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.emenia.es%2Fcomo-utilizar-un-fondo-aleatorio-para-nuestra-web%2F&amp;source=JuanDBB_Emenia&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Hay ocasiones en las que queremos que cada vez que entre un usuario a nuestra web <strong>el fondo de la misma sea elegido aleatoriamente</strong>. De esta forma podemos sorprender a nuestros usuarios con distintos diseños, distintos mensajes, etc..</p>
<p>Conseguirlo es muy sencillo combinando PHP y CSS.</p>
<p>Supongamos que tenemos una serie de imágenes para el fondo de nuestra web que se llaman: &#8220;fondo_body1.jpg&#8221; , &#8220;fondo_body2.jpg&#8221; , &#8220;fondo_body3.jpg&#8221; , &#8220;fondo_body4.jpg&#8221; , &#8220;fondo_body5.jpg&#8221;, &#8220;fondo_body6.jpg&#8221; , &#8220;fondo_body7.jpg&#8221; , &#8220;fondo_body8.jpg&#8221; , &#8220;fondo_body9.jpg&#8221; , &#8220;fondo_body10.jpg&#8221;,&#8221;fondo_body11.jpg&#8221; , &#8220;fondo_body12.jpg&#8221; , &#8220;fondo_body13.jpg&#8221; , &#8220;fondo_body14.jpg&#8221; y &#8220;fondo_body15.jpg&#8221;</p>
<p>¡Quince nada menos!  De esta manera va a ser dificil que a un usuario le salga dos veces seguidas la misma imagen&#8230;&#8230;</p>
<p>Vamos a ver línea por línea. Como vamos a introducir estilos dentro de <em>Head</em> escribiríamos:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;</pre></td></tr></table></div>

<p>A continuación abrimos php y creamos un número aleatorio utilizando PHP:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000088;">$valor</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">14</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Uso de rand(): rand(Valor minimo, Valor maximo);</span></pre></td></tr></table></div>

<p>De esta forma creamos un número aleatorio entre cero y catorce y lo almacenamos en la variable $valor. ¿Por qué empezamos por cero? Porque ahora vamos a almacenar los nombres de nuestras imágenes en una <em>array</em> o matriz, y estas comienzan a contar desde cero. Por lo tanto como tenemos quince imágenes contaríamos desde cero a catorce.</p>
<p>Almacenemos nuestras imágenes en el <em>array</em>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$imagenes</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fondo_body1.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body2.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body3.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body4.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body5.jpg&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body6.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body7.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body8.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body9.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body10.jpg&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;fondo_body11.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body12.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body13.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body14.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body15.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Como veis hemos creado un array donde hemos almacenado todos los nombres de nuestras imágenes y ese array lo hemos almacenado a su vez en la variable $imagenes.</p>
<p>Ahora vamos a escribir la línea de CSS que va a crear el fondo para nuestra web, es decir, el fondo de<em> body</em> (cerrando a continuación <em>php</em> y <em>style</em>):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;body{ background: #000 url('images/&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$imagenes</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$valor</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;') no-repeat top right fixed;}&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span> 
<span style="color: #339933;">&lt;/</span>style<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Como estamos aún con PHP la manera que utilizamos en PHP para escribir algo es a través de <em>echo</em>. A continuación sigue la instrucción de CSS que da el fondo a body pero con una peculiaridad: el nombre de la imagen que va a estar ocupando el fondo vendrá dado por las dos variables que hemos creado con anterioridad. Por ejemplo, si el número aleatorio es 3 tendremos <em>$imagenes[3]</em>, es decir, escogerá el tercer valor del <em>array</em> comenzando por cero, que es <em>fondo_body4.jpg</em>. Hay que tener cuidado con las comillas. Añadimos la variable con un punto (que es la manera de añadir con PHP) después de interrumpir con dobles comillas la instrucción normal de CSS para introducir PHP. Si seguimos con nuestro ejemplo el resultado será:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
body{ background: #000 url('images/fondo_body4.jpg') no-repeat top right fixed;}
&lt;/style&gt;</pre></td></tr></table></div>

<p>Vamos a ver ahora todas las líneas que escribiríamos dentro de <em>head</em>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
<span style="color: #000000; font-weight: bold;">&lt;?php</span> 
  <span style="color: #000088;">$valor</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">14</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Uso de rand(): rand(Valor minimo, Valor maximo);</span>
  <span style="color: #000088;">$imagenes</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fondo_body1.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body2.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body3.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body4.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body5.jpg&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body6.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body7.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body8.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body9.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body10.jpg&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;fondo_body11.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body12.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body13.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body14.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body15.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;body{ background: #000 url('images/&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$imagenes</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$valor</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;') no-repeat top right fixed;}&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span> 
&lt;/style&gt;</pre></td></tr></table></div>

<p><strong>Podemos refinar aún más nuestro código</strong>. ¿Qué pasa si de repente en vez de tener 15 imágenes queremos que sean 16? Que tenemos que cambiar el número en <em>rand</em>. ¿No podemos hacer que se cuente de manera automática el número de imágenes que hay en el <em>array</em>? Pues sí se puede. Lo haríamos así:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$imagenes</span><span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>En nuestro caso nos dará un valor de 15, ya que hay 15 imágenes en el <em>array</em>. Para llevar esto a la función que crea el número aleatorio haríamos:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"> <span style="color: #000088;">$valor</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$imagenes</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Uso de rand(): rand(Valor minimo, Valor maximo);</span></pre></td></tr></table></div>

<p>Vemos que a la función que nos cuenta el número de imágenes del array le hemos restado uno ¿Por qué? Recordad que se comienza siempre contando desde cero. Si hay una sola imagen <em>$valor</em> tendría que ser cero (un número aleatorio entre cero y cero, saldría cero, que es la primera imagen).</p>
<p>Ahora quedaría todo así:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;style type=&quot;text/css&quot; media=&quot;screen&quot;&gt;
  <span style="color: #000000; font-weight: bold;">&lt;?php</span> 
	<span style="color: #000088;">$imagenes</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fondo_body1.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body2.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body3.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body4.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body5.jpg&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body6.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body7.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body8.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body9.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body10.jpg&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;fondo_body11.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body12.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body13.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body14.jpg&quot;</span> <span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;fondo_body15.jpg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #000088;">$valor</span> <span style="color: #339933;">=</span> <span style="color: #990000;">rand</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$imagenes</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// Uso de rand(): rand(Valor minimo, Valor maximo);</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;body{ background: #000 url('images/&quot;</span><span style="color: #339933;">.</span><span style="color: #000088;">$imagenes</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$valor</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;') no-repeat top right fixed;}&quot;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span> 
&lt;/style&gt;</pre></td></tr></table></div>

<p>Fijaros en la instrucción que he incluído en body. Por supuesto que podéis cambiar como queráis lo que he puesto yo (fondo negro -#000-, situado en la parte superior de la pantalla -top- en la parte derecha -right- y que no se desplace cuando nos desplazamos hacia abajo en la página -fixed-)</p>
<h3>Más lecturas recomendadas</h3>
<p>PHP.net &#8211; <a href="http://php.net/manual/en/language.types.array.php">Arrays in PHP</a><br />
Desarrolloweb.com &#8211; <a href="http://www.desarrolloweb.com/articulos/310.php">Creación de tablas por medio de variables tipo array. Utilidad y funciones útiles relacionadas.</a></p>
<div id="crp_related"><h3>Artículos relacionados:</h3><ul><li><a href="http://www.emenia.es/utilizando-css3-hoy-2-colores-y-opacidad-utilizando-rbga/" rel="bookmark" class="crp_title">Utilizando CSS3 hoy (2): Colores y opacidad utilizando RBGA</a></li><li><a href="http://www.emenia.es/como-pre-cargar-imagenes-con-jquery/" rel="bookmark" class="crp_title">Cómo pre-cargar imágenes con jQuery</a></li><li><a href="http://www.emenia.es/curso-de-jquery-introduccion-1/" rel="bookmark" class="crp_title">Curso de jQuery (1): Introducción</a></li><li><a href="http://www.emenia.es/curso-de-jquery-3-selectores-segunda-parte/" rel="bookmark" class="crp_title">Curso de jQuery (3): Selectores, Segunda Parte</a></li><li><a href="http://www.emenia.es/utilizando-css3-hoy-3-sombras/" rel="bookmark" class="crp_title">Utilizando CSS3 hoy (3): Sombras</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.emenia.es/como-utilizar-un-fondo-aleatorio-para-nuestra-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatiza el año del copyright en tu web</title>
		<link>http://www.emenia.es/automatiza-el-ano-del-copyright-en-tu-web/</link>
		<comments>http://www.emenia.es/automatiza-el-ano-del-copyright-en-tu-web/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 06:09:02 +0000</pubDate>
		<dc:creator>Juan Diaz-Bustamante</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://emenia.es/?p=71</guid>
		<description><![CDATA[
			
				
			
		
Normalmente al pie de una página web ponemos siempre la frase de rigor en cuanto al copyright de la web (muchas veces sin haber realizado los papeleos legales, pero esa es otra historia&#8230;), como por ejemplo:

¿Pero qué sucede si en la frase pone 2009 y estamos ya en el año 2010 o en el 2011? [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.emenia.es%2Fautomatiza-el-ano-del-copyright-en-tu-web%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.emenia.es%2Fautomatiza-el-ano-del-copyright-en-tu-web%2F&amp;source=JuanDBB_Emenia&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Normalmente al pie de una página web ponemos siempre la frase de rigor en cuanto al copyright de la web (muchas veces sin haber realizado los papeleos legales, pero esa es otra historia&#8230;), como por ejemplo:</p>
<p><img src="http://emenia.es/wp-content/uploads/2009/09/copyright.gif" alt="copyright" title="copyright" width="500" height="28" class="aligncenter size-full wp-image-72" /></p>
<p>¿Pero qué sucede si en la frase pone 2009 y estamos ya en el año 2010 o en el 2011? Pues que si no hemos actualizado la fecha podríamos dar una impresión de web antigua. Vamos a ver cómo podemos actualizar el año de manera automática gracias a unas pocas líneas de PHP para que aparezca algo así:</p>
<p><img src="http://emenia.es/wp-content/uploads/2009/09/copyright_21.gif" alt="copyright_2" title="copyright_2" width="500" height="28" class="aligncenter size-full wp-image-73" /></p>
<p>Este código lo podemos incluir también en Wordpress, si así lo deseamos. El código a incluir es símplemente este:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
  <span style="color: #990000;">date_default_timezone_set</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Europe/Madrid&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #990000;">setlocale</span> <span style="color: #009900;">&#40;</span>LC_TIME<span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;spanish&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;es_ES@euro&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;es_ES&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;es&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$inicio</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">2009</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$actual</span><span style="color: #339933;">=</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Y'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$inicio</span><span style="color: #339933;">==</span><span style="color: #000088;">$actual</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'&lt;p &gt;'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$inicio</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;&lt;p&gt;<span style="color: #006699; font-weight: bold;">{$inicio}</span>-<span style="color: #006699; font-weight: bold;">{$actual}</span>&quot;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span> 
 &amp;copy; Copyright Emenia S.L. Todos los derechos reservados. &lt;/p&gt;</pre></td></tr></table></div>

<p>Como veis lo primero que hacemos es situarnos en la zona horaria peninsular y eso lo hacemos con las dos primeras líneas. Luego creamos dos variables: una $inicio que será el año desde el que comenzamos, en este caso 2009. La otra variable, $actual, obtiene el año actual de date(&#8216;Y&#8217;). Luego comparamos ambas variables. Si son iguales, sólo mostraremos una. Si son distintas (es decir, ya no estamos en el 2009) mostraremos las dos. Una vez dejamos ya php terminamos con el resto de la frase.</p>
<h3>Más lecturas recomendadas:</h3>
<p>Sobre date-default-timezone-set: <a href="http://es.php.net/manual/en/function.date-default-timezone-set.php">http://es.php.net/manual/en/function.date-default-timezone-set.php</a><br />
Sobre setlocale: <a href="http://es.php.net/manual/en/function.setlocale.php">http://es.php.net/manual/en/function.setlocale.php</a><br />
Sobre date(&#8216;Y&#8217;): <a href="http://es.php.net/manual/en/function.date.php">http://es.php.net/manual/en/function.date.php</a><br />
En el blog Digging into Wordpress aparece una solución alternativa utilizando los recursos que proporciona Wordpress: <a href="http://digwp.com/2009/08/range-copyright-dates/" title="Ir a Digging into Wordpress">http://digwp.com/2009/08/range-copyright-dates/</a></p>
<div id="crp_related"><h3>Artículos relacionados:</h3><ul><li><a href="http://www.emenia.es/lista-productos-wordpress-3/" rel="bookmark" class="crp_title">Crear una lista de productos con Wordpress 3.0 usando Entradas personalizadas, campos personalizados y taxonomías</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.emenia.es/automatiza-el-ano-del-copyright-en-tu-web/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cómo limitar el número de palabras en the_content o the_excerpt en Wordpress</title>
		<link>http://www.emenia.es/como-limitar-el-numero-de-palabras-en-the_content-o-the_excerpt-en-wordpress/</link>
		<comments>http://www.emenia.es/como-limitar-el-numero-de-palabras-en-the_content-o-the_excerpt-en-wordpress/#comments</comments>
		<pubDate>Sat, 22 Aug 2009 15:09:46 +0000</pubDate>
		<dc:creator>Juan Diaz-Bustamante</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://emenia.es/?p=48</guid>
		<description><![CDATA[
			
				
			
		
Vamos a ver una forma de limitar el número de palabras del contenido o del resumen de un artículo en Wordpress sólo cuando y donde queramos y sin alterar el código principal ni el número de caracteres en el administrador, lo cual puede ser muy útil para que todo se mantenga tal cual al actualizar [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.emenia.es%2Fcomo-limitar-el-numero-de-palabras-en-the_content-o-the_excerpt-en-wordpress%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.emenia.es%2Fcomo-limitar-el-numero-de-palabras-en-the_content-o-the_excerpt-en-wordpress%2F&amp;source=JuanDBB_Emenia&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Vamos a ver una forma de limitar el número de palabras del contenido o del resumen de un artículo en Wordpress sólo cuando y donde queramos y sin alterar el código principal ni el número de caracteres en el administrador, lo cual puede ser muy útil para que todo se mantenga tal cual al actualizar nuestra versión de Wordpress o a la hora de mostrar los resúmenes en la página principal del blog. </p>
<p>Esto lo he hecho en la portada de Emenia, que como podéis ver es una página en principio estática, donde no se publican los artículos del blog (este se hace seleccionando en el administrador de Wordpress dentro de Opciones/Lectura <em>La página inicial mostrará una página estática</em>). Si os fijáis veréis que en su lado derecho hay un cuadro con los dos últimos artículos del blog. Necesitaba incluír un número muy limitado de palabras en este resumen, pero sin afectar al número de caracteres que por defecto muestra Wordpress cuando escribimos the_excerpt() &#8211; 55 caracteres &#8211; que quería que funcionara con normalidad en el blog.</p>
<p>Voy a dividir el código en varias partes para explicarlo con más facilidad y al final incluiré el código completo.</p>
<p>Las primeras líneas lo que hacen es <strong>limitar el número de entradas que se van a mostrar a dos</strong>. Por supuesto que cambiando el número de &#8216;numberposts=2&#8242; podremos publicar más (o menos) entradas. Se crea un bucle <strong>foreach</strong> que lo envuelve todo y que finaliza con   endforeach;</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;ul&gt;
  <span style="color: #000000; font-weight: bold;">&lt;?php</span>
    <span style="color: #000088;">$recentposts</span> <span style="color: #339933;">=</span> get_posts<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'numberposts=2'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$recentposts</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$post</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">:</span>
	setup_postdata<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">?&gt;</span>
&nbsp;
 Aquí escribiremos el código que se aplicará a cada artículo
&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">endforeach</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;/ul&gt;</pre></td></tr></table></div>

<p>A continuación con the_title() obtendremos el <strong>título del artículo</strong> en forma de enlace al artículo completo gracias a the_permalink(), que escribe en enlace al artículo.</p>
<p>Y ahora necesitamos <strong>obtener el contenido del artículo y almacenarlo en una variable</strong>. No podemos usar the_content() o the_excerpt() porque ejecutan el script y muestran el contenido completo, pero sí podemos utilizar get_the content() o get_the_excerpt(). Lo almacenaremos en una variable que llamaremos $textoLargo. También vamos a almacenar el enlace correspondiente a cada artículo en una variable. Eso lo logramos con get_permalink($post->ID)</p>
<p>Vamos a verlo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;p&gt;&lt;a href=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> the_permalink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot;&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> the_title<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/a&gt;&lt;/p&gt;
<span style="color: #000000; font-weight: bold;">&lt;?php</span>  
  <span style="color: #000088;">$textoLargo</span><span style="color: #339933;">=</span> get_the_excerpt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$permalink</span> <span style="color: #339933;">=</span> get_permalink<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Ahora viene quizás la parte más compleja. Necesitamos <strong>crear una función</strong> que haga todo el trabajo cada vez que necesitemos reducir el tamaño del texto incluído en la variable $textoLargo.</p>
<p>Para ello vamos a utilizar PHP. Abrimos el archivo <strong>functions.php</strong> que se encuentra normalmente en el directorio de nuestro template, junto a todos los demás archivos, y escribimos:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> limitar_palabras<span style="color: #009900;">&#40;</span> <span style="color: #000088;">$str</span><span style="color: #339933;">,</span> <span style="color: #000088;">$num</span><span style="color: #339933;">,</span> <span style="color: #000088;">$append_str</span><span style="color: #339933;">=</span><span style="color: #0000ff;">''</span> <span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$palabras</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_split</span><span style="color: #009900;">&#40;</span> <span style="color: #0000ff;">'/[\s]+/'</span><span style="color: #339933;">,</span> <span style="color: #000088;">$str</span><span style="color: #339933;">,</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> PREG_SPLIT_OFFSET_CAPTURE <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span> <span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$palabras</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$num</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$str</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span> <span style="color: #000088;">$palabras</span><span style="color: #009900;">&#91;</span><span style="color: #000088;">$num</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#41;</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$append_str</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #990000;">unset</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$palabras</span><span style="color: #339933;">,</span> <span style="color: #000088;">$num</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">return</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span> <span style="color: #000088;">$str</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Esta función es la que va a realizar todo el trabajo. Como vemos acepta tres parámetros: $str que es la cadena de texto que vamos a acortar, $num que es el número de palabras que se mostrarán y por último cualquier cadena de texto o código que queramos unir al nuevo texto ya cortado (por defecto este parámetro será una cadena de texto vacía, de ahí las dos comillas en $append_str=&#8221;). Dentro ya de la función utilizamos preg_split que lo que hace es cortar una cadena de texto utilizando una regular expression. Podemos ver la descripción y uso de preg_split en el <a href="http://es2.php.net/manual/en/function.preg-split.php">manual de funciones de PHP</a>.</p>
<p><strong>Seguimos donde lo habíamos dejado</strong> más arriba una vez hemos guardado functions.php con la nueva función incorporada.<br />
Ahora vamos a crear una nueva variable que llamaremos <strong>$textoCorto</strong> que almacenará el texto ya cortado y que invocará la función limitar_palabras pasando estos parámetros:<br />
El texto a cortar (que está en la variable $textoLargo), el número de caracteres del nuevo texto (en este caso 13) y el texto adicional que vamos a incluir tras el texto cortado (en este caso unos corchetes con dos puntos en su interior para mostrar que hay  más texto y la palabra Más con el enlace al artículo, que habíamos guardado en la variable $permalink). Para finalizar mostramos ya en la página el texto ya cortado con un echo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">  <span style="color: #000088;">$textoCorto</span><span style="color: #339933;">=</span>limitar_palabras<span style="color: #009900;">&#40;</span><span style="color: #000088;">$textoLargo</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">13</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'&amp;#91;...&amp;#93;&amp;nbsp;&amp;nbsp;&lt;a href=&quot;'</span><span style="color: #339933;">.</span> <span style="color: #000088;">$permalink</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&quot; title=&quot;Ir al art&amp;iacute;culo&quot;&gt;M&amp;aacute;s&amp;raquo;&lt;/a&gt;'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'&lt;p&gt;'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$textoCorto</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;/p&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>¡Y eso sería todo! Ya tendríamos los dos últimos artículos con su título y en enlace al artículo, con su contenido limitado a 13 palabras y con un Más>> también enlazado al artículo completo.</p>
<p><strong>Este sería el código completo:</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;p&gt;&lt;a href=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> the_permalink<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot;&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> the_title<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/a&gt;&lt;/p&gt;
<span style="color: #000000; font-weight: bold;">&lt;?php</span> 	
   <span style="color: #000088;">$textoLargo</span><span style="color: #339933;">=</span> get_the_excerpt<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$permalink</span> <span style="color: #339933;">=</span> get_permalink<span style="color: #009900;">&#40;</span><span style="color: #000088;">$post</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ID</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$textoCorto</span><span style="color: #339933;">=</span>limitar_palabras<span style="color: #009900;">&#40;</span><span style="color: #000088;">$textoLargo</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">13</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'&amp;#91;...&amp;#93;&amp;nbsp;&amp;nbsp;&lt;a href=&quot; '</span><span style="color: #339933;">.</span> <span style="color: #000088;">$permalink</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">' &quot; title=&quot;Ir al art&amp;iacute;culo&quot;&gt;M&amp;aacute;s&amp;raquo;&lt;/a&gt;'</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'&lt;p&gt;'</span> <span style="color: #339933;">.</span> <span style="color: #000088;">$textoCorto</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;/p&gt;'</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<h3>Más lecturas recomendadas:</h3>
<p>CJD Blog &#8211; Muestra cómo crear resúmenes personalizados creando una función en Wordpress, una solución más pura de Wordpress, aunque algo más compleja: <a href="http://www.chrisjdavis.org/custom-excerpts-for-wordpress">http://www.chrisjdavis.org/custom-excerpts-for-wordpress</a></p>
<div id="crp_related"><h3>Artículos relacionados:</h3><ul><li><a href="http://www.emenia.es/como-separar-los-articulos-por-categorias-en-wordpress/" rel="bookmark" class="crp_title">Cómo separar los artículos por categorías en Wordpress</a></li><li><a href="http://www.emenia.es/como-utilizar-un-fondo-aleatorio-para-nuestra-web/" rel="bookmark" class="crp_title">Como utilizar un fondo aleatorio para nuestra web</a></li><li><a href="http://www.emenia.es/lista-productos-wordpress-3/" rel="bookmark" class="crp_title">Crear una lista de productos con Wordpress 3.0 usando Entradas personalizadas, campos personalizados y taxonomías</a></li><li><a href="http://www.emenia.es/recopilacion-de-45-trucos-para-wordpress/" rel="bookmark" class="crp_title">Recopilación de 45 trucos para Wordpress</a></li><li><a href="http://www.emenia.es/nuevo-en-wordpress-2-9-miniaturas-de-entrada-post-thumbnails/" rel="bookmark" class="crp_title">Nuevo en Wordpress 2.9: Miniaturas de Entrada (Post Thumbnails)</a></li></ul></div>]]></content:encoded>
			<wfw:commentRss>http://www.emenia.es/como-limitar-el-numero-de-palabras-en-the_content-o-the_excerpt-en-wordpress/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
