Estas en: Home > PHP

Entradas etiquetadas con PHP

Integración continua: Coding standards para PHP

0

¿Qué son los coding standards?

Los coding standards son estándares de código, dicho de otra manera, son reglas que indican como debe escribirse el código, cuantos espacios debe tener una tabulación, en qué línea debe ubicarse un «else», cómo debe escribir una función, método o clase, etc.

Los coding standards se utilizan principalmente en los CMS como WordPress o Drupal, esto permite que el código sea mucho más legible por diferentes personas.

La aplicación que vamos a instalar es PHPCS que nos permitirá revisar el código y comprobar si estamos siguiendo el standard correctamente.

Instalación

La instalación es sencilla, como prácticamente la mayoría de herramientas que utilizaremos para nuestro servidor de integración.

sudo−DVFMTSC−> apt−DVFMTSC−>−get−DVFMTSC−> install−DVFMTSC−> php−DVFMTSC−>−pear
sudo−DVFMTSC−> pear−DVFMTSC−> install−DVFMTSC−> php_CodeSniffer

En Ubuntu la aplicación se instala en /usr/share/php/PHP.

Una vez instalado, será necesario dar permisos de lectura al usuario www-data:

cd−DVFMTSC−> /usr/share/php/PHP
sudo−DVFMTSC−> chown−DVFMTSC−> −DVFMTSC−>−R−DVFMTSC−> www−DVFMTSC−>−data:www−DVFMTSC−>−data−DVFMTSC−> CodeSniffer
sudo−DVFMTSC−> chown−DVFMTSC−> www−DVFMTSC−>−data:www−DVFMTSC−>−data−DVFMTSC−> CodeSniffer.php
sudo−DVFMTSC−> chmod−DVFMTSC−> −DVFMTSC−>−R−DVFMTSC−> 775−DVFMTSC−> CodeSniffer
sudo−DVFMTSC−> chmod−DVFMTSC−> −DVFMTSC−>−R−DVFMTSC−> 775−DVFMTSC−> CodeSniffer.php

Con esto ya lo tenemos instalado.

En futuros post, instalaremos algunos Coding Standards y veremos el funcionamiento de esta herramienta.

Integración continua: instalando y configurando Jenkins

0

Ya vistes la checklist del último post: https://www.interadictos.es/2014/08/11/integracion-continua-primeros-pasos/, ahora vamos a empezar a instalar y configurar algunas herramientas, para ir poco a poco uniéndolas.

¿Qué es Jenkins?

Jenkins es nuestro servidor de integración continua. Es una aplicación que permite automatizar una lista de tareas que le indiquemos. Estas tareas pueden ser iniciadas de forma manual, pero lo habitual será llamar a la primera tarea de la lista cada vez que se realice un commit en el repositorio, e ir concatenando tareas hasta finalizar la lista completa. Tranquilo si no te haces aun a la idea, a medida que vayamos avanzando con esta guía lo iras entendiendo.

Instalando Jenkins

Primero descargamos la key del servidor de Jenkins, que nos permitirá añadirlo al archivo sources.list:

wget −q −O   class="external free" style="color: #663366;" href="http://pkg.jenkins−ci.org/debian/jenkins−ci.org.key" rel="nofollow">http://pkg.jenkins−ci.org/debian/jenkins−ci.org.key | sudo apt−key add 

A continuación lo añadimos al archivo sources.list. Puedes añadirlo de esta manera o añadirlo a mano:

sudo sh −c 'echo deb  class="external free" style="color: #663366;" href="http://pkg.jenkins−ci.org/debian" rel="nofollow">http://pkg.jenkins−ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'

Actuliazamos la lista de paquetes e instalamos:

sudo apt−get update
sudo apt−get install jenkins

Ahora necesitamos poder acceder a él a través de la red, para ello vamos a crear el subdominio jenkins.ic.net. Para poder acceder por el subdominio jenkins.ic.net es necesario crear un virtual host con proxy inverso, para ello instalamos varios módulos de Apache2 necesarios:

sudo a2enmod proxy
sudo a2enmod headers
sudo a2enmod deflate
sudo a2enmod proxy_http

Ahora creamos un virtualhost en /etc/apache2/sites-available llamado 001-jenkins.ic.net.conf (Podeis usar el nombre que quieras), con el siguiente contenido

 *:80>
        ServerName jenkins.ic.net  

         *>
                Order deny,allow
                Allow from all
         

        ProxyPreserveHost On
        ProxyPass /  class="external free" style="color: #663366;" href="http://localhost:8080/" rel="nofollow">http://localhost:8080/
        ProxyPassReverse /  class="external free" style="color: #663366;" href="http://localhost:8080/" rel="nofollow">http://localhost:8080/

La ruta habitual para acceder a Jenkins sería http://localhost:8080, si pudieramos acceder desde el mismo servidor de integración continua, si lo hicieramos desde fuera sería http://ic.net:8080. Para evitar tener que recordar el número de puerto utilizamos el archivo anterior. Nos facilitará la vida.

Ahora creamos un enlace simbólico de este archivo en /etc/apache2/sites-enabled.

sudo ln −s /etc/apache2/sites−available/001−jenkins.ic.net.conf /etc/apache2/sites−enabled/001−jenkins.ic.net.conf

Reiniciamos apache con:

sudo /etc/init.d/apache2 reload

En nuestro ordenador tendremos que editar el archivo hosts, para indicarle al pc a qué ip debe dirigirse para encontrar el alojamiento de jenkins.ic.net. Añadimos la siguiente línea al archivo (sustituye la IP por la de tu servidor de integración continua):

192.168.1.40 jenkins.ic.net

Ahora podrás escribir el subdominio en el navegador para acceder a la página principal de Jenkins.

A partir de aquí te recomiendo que explores todas las opciones de Jenkins, además de echarle un ojo a la documentación: https://wiki.jenkins-ci.org/display/JENKINS/Use+Jenkins

En la administración de Jenkins puedes acceder al apartado de plugins, revísalos y podrás hacerte una idea de las posibilidades de esta herramienta.

Integración continua: primeros pasos

0

Ya expliqué la semana pasada qué era eso de la integración continua, pues bien, ahora toca dar los primeros pasos. Obviamente necesitamos un ordenador que haga de servidor, una máquina virtual, o bien un servidor de verdad si lo que pretendes es utilizar de forma profesional.

Como sistema operativo para esta guía utilizaré Ubuntu 14.04. Tú puedes usar el que quieras pero tal vez te resulte más complicado encontrar algún software, con lo que tendrás que investigar más.

El hardware a usar dependerá de las necesidades que tengas, o para lo que quieras un servidor de integración continua. En mi caso utilizo un pc de gama baja con micro AMD, 8 GB de RAM, sin teclado, ratón, ni monitor (y por tanto sin escritorio gráfico), y con una tarjeta WiFi para conectar a internet. Y esto, para mí, es suficiente. Si lo fueses a usar en un grupo de desarrollo, lo mejor es usar un VPS o un servidor dedicado, ya que mejorará en gran medida el rendimiento.

Ya tenemos el hardware listo y nuestro sistema operativo está instalado, por tanto vamos a iniciar los primeros pasos para crear nuestro servidor de integración continua.

(más…)

Integración continua: Introducción

0

Supongo que os preguntaréis qué es eso de la integración continua, pues bien, os explico: se considera Integración Continua al conjunto de metodologías y procesos que se ejecutan durante el desarrollo de un proyecto de programación, con la diferencia de que estos procesos están centralizados y automatizados, lo que permite ejecutarlos cada pocas horas.

Dentro de los procesos automatizados se encuentran la descarga de los repositorios, la comprobación de los estándares de codificación, la ejecución de los test unitarios, la actualización de la base de datos, el despliegue al servidor de producción, etc. Cualquier proceso que se ejecute durante el desarrollo de un proyecto se puede integrar en este sistema.

Esta forma de trabajar nos permite a los desarrolladores detectar, antes de poner en producción el proyecto, posibles errores o ineficiencias, pudiendo solucionarlos y mejorando con ello la calidad del software que generamos.

Sirva este pequeño artículo como introducción a esta nueva sección del blog, ya que durante las próximas semanas iré publicando nuevos artículos para que podáis montar vuestro propio servidor de integración continua, me centraré en la automatización de procesos en proyectos PHP, ya sean basados en Frameworks (Symfony, Zend, etc.), CMS (WordPress, PrestaShop, etc.) o creados desde cero, aunque es muy posible que muchas cosas de las que os explique podáis utilizarlas para otros lenguajes de programación. Os explicaré tanto la instalación del software necesario como su configuración, además de como unir todo el software para que se ejecute de forma automática.

De momento os dejo con varios links para que le vayáis echando un ojo a eso de la Integración Continua:

– http://es.wikipedia.org/wiki/Integraci%C3%B3n_continua

Desarrollo PHP avanzado

Drupal logo

Crear un rol de usuario en Drupal 7 sin usar la interfaz de administración

0

Normalmente cuando trabajamos con Drupal utilizamos la interfaz de administración para configurar nuestra aplicación web, y por norma general esto es suficiente para lo que queremos hacer. Sin embargo, en otros casos nos encontramos con que necesitamos generar nuevos roles de usuario (administrador, usuario identificado, etc.) además de los que vienen por defecto en Drupal, pero a través del código fuente, ya sea porque trabajamos dentro de un equipo de desarrollo y no tiene sentido estar compartiendo la bd entre todos los desarrolladores cada vez que se realiza un cambio de configuración (además de poco productivo terminará provocando perdidas de datos y errores), o porque estamos desarrollando un perfil de instalación y queremos reducir al mínimo los pasos manuales que hay que realizar para instalar nuestra aplicación web, por ejemplo.

Para ello debemos añadir a nuestra aplicación el siguiente código:

 

$new_user_role = new stdClass();
$new_user_role->name = 'moderator';
$new_user_role->weight = 4;
user_role_save($new_user_rol);

Como ves, el código es bastante sencillo. En primer lugar creamos una instancia de la clase stdClass(); a continuación le damos un nombre y un peso (recuerda que el rol de administrador es el 3, que es el más alto de lo roles por defecto de Drupal), y por último lo guardamos.

Cron Job WordPress

WordPress 3.x para desarrolladores: Plugins, conceptos básicos

0

Un plugin WordPress es un programa, o un conjunto de una o más funciones, escritas en el lenguaje de scripting PHP, que añade un conjunto específico de características o servicios para el weblog WordPress, los cuales pueden ser integrados sin problemas con el weblog usando puntos de acceso y métodos proporcionados por la API.

 

Nombres, archivos y ubicaciones

La primera tarea a la hora de crear un plugin de WordPress es pensar en qué va a hacer el plugin, y crear un (ojalá único) nombre para él. Compruebe en Plugin y en otros repositorios referidos en el enlace, que el nombre no exista ya; se puede hacer, también, una búsqueda en Google. Muchos desarrolladores eligen nombres que describen, de alguna manera, lo que hace el plugin; por ejemplo, un plugin que haga algo relacionado con el tiempo, podría llevar la palabra «tiempo» en su nombre. El nombre puede tener varias palabras.

 

El siguiente paso es crear un archivo PHP con un nombre, derivado del nombre que usted ha elegido para el plugin. Por ejemplo, si su plugin se llamará «funcionalidad maravillosa», usted podría nombrar al archivo PHP funcimara.php. De nuevo, intente elegir un nombre único. La gente que utilice su plugin, lo pondrá en el directorio de WordPress, en su instalación wp-content/plugins/, de forma que no puede haber dos plugin distintos con el mismo nombre de archivo PHP.

Otra opción es separar el plugin en varios archivos. Su plugin WordPress debe tener al menos un archivo PHP; además puede contener archivos JavaScript, archivos CSS, archivos de imagen, archivos de localización, etc. Si hay varios archivos, elija un nombre único para una carpeta de archivos y para el archivo PHP principal, tales como funcimara y funcimara.php en este ejemplo, coloque todos los archivos del plugin en la carpeta y diga a los usuarios que copien toda la carpeta en wp-content/plugins/.

En el resto de este artículo, nos referiremos al archivo PHP principal como «el archivo PHP del Plugin», ya esté en wp-content/plugins/ o en un subdirectorio.

 

Información Estándar del Plugin

Las primeras líneas del archivo PHP principal del plugin deben contener la cabecera estándar de información del plugin. Esta cabecera permite a WordPress reconocer que el plugin existe, y ponerlo en la pantalla de gestión para que pueda ser activado, cargado y ejecutar sus funciones. Sin esta cabecera, su plugin no podrá ser activado ni funcionar. Este es el formato de la cabecera:

<?php
/*
Plugin Name: Nombre del plugin
Plugin URI: http://URI_De_La_Página_Que_Describe_el_Plugin_y_Actualizaciones
Description: Una breve descripción del plugin.
Version: El número de versión del plugin e.j.: 1.0
Author: Nombre del autor del plugin
Author URI: http://URI_del_Autor_del_Plugin
License: Un nombre de licencia "pegadizo" e.j. GPL2
*/
?>

El mínimo de información que WordPress necesita para reconocer su plugin es el nombre del mismo. El resto de la información (si está presente) se utilizará para crear la tabla de plugin en la pantalla de gestión de plugins. El orden de las líneas no es importante.

La línea de licencia debería ser un identificador común, corto, para señalar bajo que licencia se distribuye el código y está destinado a ser una forma sencilla de ser explícito acerca de la licencia del mismo.

 

Sugerencias sobre Desarrollo de Plugin

Esta última sección contiene sugerencias aleatorias sobre el desarrollo de plugin.

  • El código de un plugin WordPress debería seguir los Estándar de WordPress Coding. Por favor, también considere los estándarDocumentación en Línea.
  • Todas las funciones en su plugin necesitan tener nombres únicos que sean diferentes de los de funciones del núcleo de WordPress, otros plugins y plantillas. Por esta razón, es una buena idea utilizar un prefijo de nombre de función en todos sus plugins. Otra posibilidad es definir sus funciones de plufin dentro de una clase (que, a su vez, necesita tener un nombre único).
  • No utilice el prefijo de bases de datos (normalmente «wp_»)de WordPress directamente en sus plugins. Asegúrese de que utiliza la variable $wpdb->prefijo en su lugar.
  • Leer la base de datos es barato, pero escribir es caro. Las bases de datos son excepcionalmente buenas recuperando datos y ofreciéndosela a usted y estas operaciones son (normalmente) veloces como el rayo. El hacer cambios en la base de datos, es un proceso más complejo, y más caro desde el punto de vista computacional. Como resultado, intente minimizar la cantidad deescritura que usted hace en la base de datos. Deje todo preparado en su código primero, de forma que usted hace las operaciones de escritura estrictamente necesarias.
  • SELECT solo lo que se necesita. A pesar de que las bases de dato recuperan información realmente rápido, usted debería intentar de reducir la carga sobre la base de datos, seleccionando solo la información sobre la que quiere trabajar. Si usted necesita únicamente contar el número de líneas de una tabla no haga SELECT * FROM, porque se cargarán todos los datos de cada registro, desaprovechando memoria. Así mismo, si solo necesita el post_id y el post_author en el plugin, simplemente SELECTesos campos específicos, para minimizar la carga de la base de datos. Recuerde: cientos de procesos diferentes pueden estar consultando la base de datos al mismo tiempo. La base de datos y el servidor tienen recursos limitados para atender dichos procesos. Aprender como minimizar el impacto de sus plugins en la base de datos asegurará que el suyo no sea el señalado como culpable de abuso de recursos.
  • Elimine errores de PHP en sus plugin. Añada define('WP_DEBUG', true); a su archivo wp-config.php, compruebe toda la funcionabilidad del plugin, y chequee si hay errores y/o avisos. Arregle cualquier incidencia y continue en modo debug hasta que se hayan eliminado todos los errores.
  • Intente no utilizar directamente las etiquetas <script> y <style> – en su lugar utilice las funciones recomendadaswp_enqueue_style() y wp_enqueue_script(). Estas ayudan a eliminar scripts y estilos duplicados y, además, introducen soporte de dependencias. Consulte post de las siguientes personas para más información: Ozh RichardsonArtem Russakovskii, yVladimir Prelovac.
Cron Job WordPress

PHP Code Sniffer, WordPress y coding standards

0

Llevo varias semanas mirando información sobre integración continua y desde hace varios días estoy dándole caña a todas las herramientas que hay que instalar y configurar.

Entre esas herramientas se encuentra PHP Code Sniffer, que permite revisar el código en busca de violaciones de la codificación estándar que se esté usando.

Los coding standards, para el que no los conozca son como las guías de estilo que tienen los periódicos, en ellos se especifica la tipografía a usar tanto en los titulares como en el contenido, el tamaño del texto, la ubicación, etc. En programación ocurre igual, solo que aquí no se habla de tipografías, sino de espacios en blanco después de la apertura del paréntesis de una función, y antes del cierre de este, número de espacios en blanco para sangrar las líneas, o tabulaciones, ubicación de las llaves de apertura, si en la misma línea o en la inferior, etc. Podéis ver el coding standard de pear aquí: http://pear.php.net/manual/en/standards.php.

En WordPress también existe un coding standard derivado del de PEAR: http://codex.wordpress.org/WordPress_Coding_Standards el cual debería ser utilizado por todos para mantener el código de nuestros temas y plugins lo más estándar posible.

Digo debería  porque si ejecutas el sniffer sobre el código de WordPress, no hay ni un solo archivo que no incumpla el coding standard. Es bastante frustrante después de toda una tarde de configuración, aprendizaje, errores, pruebas, y más configuración, encontrarte que no se sigue el estándar, excepto en el código nuevo. Aquí lo explican: https://groups.google.com/forum/?fromgroups=#!msg/wp-hackers/Exg0i8wZEEQ/K1_TxvSs44cJ.

Así que solo queda buscar la forma de configurar la herramienta para que no procese los archivos de WordPress y que solo se aplique en las plantillas y plugins que yo desarrolle.

 

PD: Miedo me da pasarle el phpcs a los plugins de WordPress.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, category.php, author.php, archive.php y 404.php

0

Estas son las últimas plantillas que crearemos para nuestro tema.

 

CATEGORY.PHP

Creamos el archivo category.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying Category Archive pages.
 *
 * @package WordPress
 * @subpackage New_Theme
 */

get_header(); ?>

		<section id="primary">
			<div id="content" role="main">

			<?php if ( have_posts() ) : ?>

				<header class="page-header">
					<h1 class="page-title"><?php
						printf( __( 'Category Archives: %s', 'newtheme' ), '<span>' . single_cat_title( '', false ) . '</span>' );
					?></h1>

					<?php
						$category_description = category_description();
						if ( ! empty( $category_description ) )
							echo apply_filters( 'category_archive_meta', '<div class="category-archive-meta">' . $category_description . '</div>' );
					?>
				</header>

				<?php newtheme_content_nav( 'nav-above' ); ?>

				<?php /* Start the Loop */ ?>
				<?php while ( have_posts() ) : the_post(); ?>

					<?php
						/* Include the Post-Format-specific template for the content.
						 * If you want to overload this in a child theme then include a file
						 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );
					?>

				<?php endwhile; ?>

				<?php newtheme_content_nav( 'nav-below' ); ?>

			<?php else : ?>

				<article id="post-0" class="post no-results not-found">
					<header class="entry-header">
						<h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
					</header><!-- .entry-header -->

					<div class="entry-content">
						<p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
						<?php get_search_form(); ?>
					</div><!-- .entry-content -->
				</article><!-- #post-0 -->

			<?php endif; ?>

			</div><!-- #content -->
		</section><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

[/codesyntax]

Esta plantilla está creada para mostrar los post que están en una misma categoría. La estructura de la página es idéntica al del resto que hemos visto del estilo.

 

AUTHOR.PHP

Creamos el archivo author-php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying Author Archive pages.
 *
 * @package WordPress
 * @subpackage New_Theme
 */

get_header(); ?>

		<section id="primary">
			<div id="content" role="main">

			<?php if ( have_posts() ) : ?>

				<?php
					/* Queue the first post, that way we know
					 * what author we're dealing with (if that is the case).
					 *
					 * We reset this later so we can run the loop
					 * properly with a call to rewind_posts().
					 */
					the_post();
				?>

				<header class="page-header">
					<h1 class="page-title author"><?php printf( __( 'Author Archives: %s', 'newtheme' ), '<span class="vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( "ID" ) ) ) . '" title="' . esc_attr( get_the_author() ) . '" rel="me">' . get_the_author() . '</a></span>' ); ?></h1>
				</header>

				<?php
					/* Since we called the_post() above, we need to
					 * rewind the loop back to the beginning that way
					 * we can run the loop properly, in full.
					 */
					rewind_posts();
				?>

				<?php newtheme_content_nav( 'nav-above' ); ?>

				<?php
				// If a user has filled out their description, show a bio on their entries.
				if ( get_the_author_meta( 'description' ) ) : ?>
				<div id="author-info">
					<div id="author-avatar">
						<?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'newtheme_author_bio_avatar_size', 60 ) ); ?>
					</div><!-- #author-avatar -->
					<div id="author-description">
						<h2><?php printf( __( 'About %s', 'newtheme' ), get_the_author() ); ?></h2>
						<?php the_author_meta( 'description' ); ?>
					</div><!-- #author-description	-->
				</div><!-- #author-info -->
				<?php endif; ?>

				<?php /* Start the Loop */ ?>
				<?php while ( have_posts() ) : the_post(); ?>

					<?php
						/* Include the Post-Format-specific template for the content.
						 * If you want to overload this in a child theme then include a file
						 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );
					?>

				<?php endwhile; ?>

				<?php newtheme_content_nav( 'nav-below' ); ?>

			<?php else : ?>

				<article id="post-0" class="post no-results not-found">
					<header class="entry-header">
						<h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
					</header><!-- .entry-header -->

					<div class="entry-content">
						<p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
						<?php get_search_form(); ?>
					</div><!-- .entry-content -->
				</article><!-- #post-0 -->

			<?php endif; ?>

			</div><!-- #content -->
		</section><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

[/codesyntax]

Esta plantilla muestra los post que un autor haya escrito. Lo más relevante del código es que para obtener los datos del autor se recupera el primer post, se genera la cabecera del contenido y después se reinicia el dataset para mostrar los post desde el primero, utilizando para ello la función rewind_posts().

 

ARCHIVE.PHP

Creamos el archivo archive.php y añadimos el siguiete código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying Archive pages.
 *
 * Used to display archive-type pages if nothing more specific matches a query.
 * For example, puts together date-based pages if no date.php file exists.
 *
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Twenty_Eleven
 */

get_header(); ?>

		<section id="primary">
			<div id="content" role="main">

			<?php if ( have_posts() ) : ?>

				<header class="page-header">
					<h1 class="page-title">
						<?php if ( is_day() ) : ?>
							<?php printf( __( 'Daily Archives: %s', 'newtheme' ), '<span>' . get_the_date() . '</span>' ); ?>
						<?php elseif ( is_month() ) : ?>
							<?php printf( __( 'Monthly Archives: %s', 'newtheme' ), '<span>' . get_the_date( _x( 'F Y', 'monthly archives date format', 'newtheme' ) ) . '</span>' ); ?>
						<?php elseif ( is_year() ) : ?>
							<?php printf( __( 'Yearly Archives: %s', 'newtheme' ), '<span>' . get_the_date( _x( 'Y', 'yearly archives date format', 'newtheme' ) ) . '</span>' ); ?>
						<?php else : ?>
							<?php _e( 'Blog Archives', 'newtheme' ); ?>
						<?php endif; ?>
					</h1>
				</header>

				<?php newtheme_content_nav( 'nav-above' ); ?>

				<?php /* Start the Loop */ ?>
				<?php while ( have_posts() ) : the_post(); ?>

					<?php
						/* Include the Post-Format-specific template for the content.
						 * If you want to overload this in a child theme then include a file
						 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );
					?>

				<?php endwhile; ?>

				<?php newtheme_content_nav( 'nav-below' ); ?>

			<?php else : ?>

				<article id="post-0" class="post no-results not-found">
					<header class="entry-header">
						<h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
					</header><!-- .entry-header -->

					<div class="entry-content">
						<p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
						<?php get_search_form(); ?>
					</div><!-- .entry-content -->
				</article><!-- #post-0 -->

			<?php endif; ?>

			</div><!-- #content -->
		</section><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

[/codesyntax]

Esta plantilla muestra los post publicados en una fecha o entre fechas concretas.

Cron Job WordPress

WordPress 3.x para desarrolladores: temas y plantillas, tag.php, search.php, searchform.php e image.php

0

Llegamos a las penúltimas plantillas por comentar.

 

TAG.PHP

Creamos el archivo tag.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template used to display Tag Archive pages
 *
 * @package WordPress
 * @subpackage New_Theme
 */

get_header(); ?>

		<section id="primary">
			<div id="content" role="main">

			<?php if ( have_posts() ) : ?>

				<header class="page-header">
					<h1 class="page-title"><?php
						printf( __( 'Tag Archives: %s', 'newtheme' ), '<span>' . single_tag_title( '', false ) . '</span>' );
					?></h1>

					<?php
						$tag_description = tag_description();
						if ( ! empty( $tag_description ) )
							echo apply_filters( 'tag_archive_meta', '<div class="tag-archive-meta">' . $tag_description . '</div>' );
					?>
				</header>

				<?php newtheme_content_nav( 'nav-above' ); ?>

				<?php /* Start the Loop */ ?>
				<?php while ( have_posts() ) : the_post(); ?>

					<?php
						/* Include the Post-Format-specific template for the content.
						 * If you want to overload this in a child theme then include a file
						 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );
					?>

				<?php endwhile; ?>

				<?php newtheme_content_nav( 'nav-below' ); ?>

			<?php else : ?>

				<article id="post-0" class="post no-results not-found">
					<header class="entry-header">
						<h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
					</header><!-- .entry-header -->

					<div class="entry-content">
						<p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
						<?php get_search_form(); ?>
					</div><!-- .entry-content -->
				</article><!-- #post-0 -->

			<?php endif; ?>

			</div><!-- #content -->
		</section><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

[/codesyntax]

Prácticamente es idéntico al resto de plantillas del estilo que hemos visto. En este caso muestra un listado de post por la etiqueta elegida.

 

SEARCH.PHP

Creamos el archivo search.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying Search Results pages.
 *
 * @package WordPress
 * @subpackage New_Theme
 */

get_header(); ?>

		<section id="primary">
			<div id="content" role="main">

			<?php if ( have_posts() ) : ?>

				<header class="page-header">
					<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'newtheme' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
				</header>

				<?php newtheme_content_nav( 'nav-above' ); ?>

				<?php /* Start the Loop */ ?>
				<?php while ( have_posts() ) : the_post(); ?>

					<?php
						/* Include the Post-Format-specific template for the content.
						 * If you want to overload this in a child theme then include a file
						 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
						 */
						get_template_part( 'content', get_post_format() );
					?>

				<?php endwhile; ?>

				<?php newtheme_content_nav( 'nav-below' ); ?>

			<?php else : ?>

				<article id="post-0" class="post no-results not-found">
					<header class="entry-header">
						<h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
					</header><!-- .entry-header -->

					<div class="entry-content">
						<p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'newtheme' ); ?></p>
						<?php get_search_form(); ?>
					</div><!-- .entry-content -->
				</article><!-- #post-0 -->

			<?php endif; ?>

			</div><!-- #content -->
		</section><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

[/codesyntax]

Esta plantilla es la que muestra el listado de post que coinciden con la búsqueda que realiza el usuario.

 

SEARCHFORM.PHP

Creamos el archivo searchform.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying search forms in Twenty Eleven
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>
	<form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
		<label for="s" class="assistive-text"><?php _e( 'Search', 'newtheme' ); ?></label>
		<input type="text" class="field" name="s" id="s" placeholder="<?php esc_attr_e( 'Search', 'newtheme' ); ?>" />
		<input type="submit" class="submit" name="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search', 'newtheme' ); ?>" />
	</form>

[/codesyntax]

Esta plantilla es la que genera el formulario de búsqueda. Como ves no tiene mucho que explicar.

 

IMAGE.PHP

Creamos el archivo image.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying image attachments.
 *
 * @package WordPress
 * @subpackage New_Theme
 */

get_header(); ?>

		<div id="primary" class="image-attachment">
			<div id="content" role="main">

			<?php while ( have_posts() ) : the_post(); ?>

				<nav id="nav-single">
					<h3 class="assistive-text"><?php _e( 'Image navigation', 'newtheme' ); ?></h3>
					<span class="nav-previous"><?php previous_image_link( false, __( '&larr; Previous' , 'newtheme' ) ); ?></span>
					<span class="nav-next"><?php next_image_link( false, __( 'Next &rarr;' , 'newtheme' ) ); ?></span>
				</nav><!-- #nav-single -->

					<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
						<header class="entry-header">
							<h1 class="entry-title"><?php the_title(); ?></h1>

							<div class="entry-meta">
								<?php
									$metadata = wp_get_attachment_metadata();
									printf( __( '<span class="meta-prep meta-prep-entry-date">Published </span> <span class="entry-date"><abbr class="published" title="%1$s">%2$s</abbr></span> at <a href="%3$s" title="Link to full-size image">%4$s &times; %5$s</a> in <a href="%6$s" title="Return to %7$s" rel="gallery">%8$s</a>', 'newtheme' ),
										esc_attr( get_the_time() ),
										get_the_date(),
										esc_url( wp_get_attachment_url() ),
										$metadata['width'],
										$metadata['height'],
										esc_url( get_permalink( $post->post_parent ) ),
										esc_attr( strip_tags( get_the_title( $post->post_parent ) ) ),
										get_the_title( $post->post_parent )
									);
								?>
								<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
							</div><!-- .entry-meta -->

						</header><!-- .entry-header -->

						<div class="entry-content">

							<div class="entry-attachment">
								<div class="attachment">
<?php
	/**
	 * Grab the IDs of all the image attachments in a gallery so we can get the URL of the next adjacent image in a gallery,
	 * or the first image (if we're looking at the last image in a gallery), or, in a gallery of one, just the link to that image file
	 */
	$attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );
	foreach ( $attachments as $k => $attachment ) {
		if ( $attachment->ID == $post->ID )
			break;
	}
	$k++;
	// If there is more than 1 attachment in a gallery
	if ( count( $attachments ) > 1 ) {
		if ( isset( $attachments[ $k ] ) )
			// get the URL of the next image attachment
			$next_attachment_url = get_attachment_link( $attachments[ $k ]->ID );
		else
			// or get the URL of the first image attachment
			$next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID );
	} else {
		// or, if there's only 1 image, get the URL of the image
		$next_attachment_url = wp_get_attachment_url();
	}
?>
									<a href="<?php echo esc_url( $next_attachment_url ); ?>" title="<?php the_title_attribute(); ?>" rel="attachment"><?php
									$attachment_size = apply_filters( 'newtheme_attachment_size', 848 );
									echo wp_get_attachment_image( $post->ID, array( $attachment_size, 1024 ) ); // filterable image width with 1024px limit for image height.
									?></a>

									<?php if ( ! empty( $post->post_excerpt ) ) : ?>
									<div class="entry-caption">
										<?php the_excerpt(); ?>
									</div>
									<?php endif; ?>
								</div><!-- .attachment -->

							</div><!-- .entry-attachment -->

							<div class="entry-description">
								<?php the_content(); ?>
								<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
							</div><!-- .entry-description -->

						</div><!-- .entry-content -->

					</article><!-- #post-<?php the_ID(); ?> -->

					<?php comments_template(); ?>

				<?php endwhile; // end of the loop. ?>

			</div><!-- #content -->
		</div><!-- #primary -->

<?php get_footer(); ?>

[/codesyntax]

Esta plantilla nos permite crear una galería de imágenes simplemente añadiendo las imágenes desde la administración.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, showcase.php y content-intro.php

0

Estas dos plantillas permiten crear un nuevo formato de página reestructurando los sidebars y los posts.

 

SHOWCASE.PHP

Creamos el archivo showcase.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * Template Name: Showcase Template
 * Description: A Page Template that showcases Sticky Posts, Asides, and Blog Posts
 *
 * The showcase template in New Theme consists of a featured posts section using sticky posts,
 * another recent posts area (with the latest post shown in full and the rest as a list)
 * and a left sidebar holding aside posts.
 *
 * We are creating two queries to fetch the proper posts and a custom widget for the sidebar.
 *
 * @package WordPress
 * @subpackage New_Theme
 */

// Enqueue showcase script for the slider
wp_enqueue_script( 'newtheme-showcase', get_template_directory_uri() . '/js/showcase.js', array( 'jquery' ), '2011-04-28' );

get_header(); ?>

		<div id="primary" class="showcase">
			<div id="content" role="main">

				<?php while ( have_posts() ) : the_post(); ?>

				<?php
					/**
					 * We are using a heading by rendering the_content
					 * If we have content for this page, let's display it.
					 */
					if ( '' != get_the_content() )
						get_template_part( 'content', 'intro' );
				?>

				<?php endwhile; ?>

				<?php
					/**
					 * Begin the featured posts section.
					 *
					 * See if we have any sticky posts and use them to create our featured posts.
					 * We limit the featured posts at ten.
					 */
					$sticky = get_option( 'sticky_posts' );

					// Proceed only if sticky posts exist.
					if ( ! empty( $sticky ) ) :

					$featured_args = array(
						'post__in' => $sticky,
						'post_status' => 'publish',
						'posts_per_page' => 10,
						'no_found_rows' => true,
					);

					// The Featured Posts query.
					$featured = new WP_Query( $featured_args );

					// Proceed only if published posts exist
					if ( $featured->have_posts() ) :

					/**
					 * We will need to count featured posts starting from zero
					 * to create the slider navigation.
					 */
					$counter_slider = 0;

					// Compatibility with versions of WordPress prior to 3.4.
					if ( function_exists( 'get_custom_header' ) )
						$header_image_width = get_theme_support( 'custom-header', 'width' );
					else
						$header_image_width = HEADER_IMAGE_WIDTH;
				?>

				<div class="featured-posts">
					<h1 class="showcase-heading"><?php _e( 'Featured Post', 'newtheme' ); ?></h1>

				<?php
					// Let's roll.
					while ( $featured->have_posts() ) : $featured->the_post();

					// Increase the counter.
					$counter_slider++;

					/**
					 * We're going to add a class to our featured post for featured images
					 * by default it'll have the feature-text class.
					 */
					$feature_class = 'feature-text';

					if ( has_post_thumbnail() ) {
						// ... but if it has a featured image let's add some class
						$feature_class = 'feature-image small';

						// Hang on. Let's check this here image out.
						$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( $header_image_width, $header_image_width ) );

						// Is it bigger than or equal to our header?
						if ( $image[1] >= $header_image_width ) {
							// If bigger, let's add a BIGGER class. It's EXTRA classy now.
							$feature_class = 'feature-image large';
						}
					}
					?>

					<section class="featured-post <?php echo $feature_class; ?>" id="featured-post-<?php echo $counter_slider; ?>">

						<?php
							/**
							 * If the thumbnail is as big as the header image
							 * make it a large featured post, otherwise render it small
							 */
							if ( has_post_thumbnail() ) {
								if ( $image[1] >= $header_image_width )
									$thumbnail_size = 'large-feature';
								else
									$thumbnail_size = 'small-feature';
								?>
								<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail( $thumbnail_size ); ?></a>
								<?php
							}
						?>
						<?php get_template_part( 'content', 'featured' ); ?>
					</section>
				<?php endwhile;	?>

				<?php
					// Show slider only if we have more than one featured post.
					if ( $featured->post_count > 1 ) :
				?>
				<nav class="feature-slider">
					<ul>
					<?php

						// Reset the counter so that we end up with matching elements
				    	$counter_slider = 0;

						// Begin from zero
				    	rewind_posts();

						// Let's roll again.
				    	while ( $featured->have_posts() ) : $featured->the_post();
				    		$counter_slider++;
							if ( 1 == $counter_slider )
								$class = 'class="active"';
							else
								$class = '';
				    	?>
						<li><a href="#featured-post-<?php echo $counter_slider; ?>" title="<?php printf( esc_attr__( 'Featuring: %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" <?php echo $class; ?>></a></li>
					<?php endwhile;	?>
					</ul>
				</nav>
				<?php endif; // End check for more than one sticky post. ?>
				</div><!-- .featured-posts -->
				<?php endif; // End check for published posts. ?>
				<?php endif; // End check for sticky posts. ?>

				<section class="recent-posts">
					<h1 class="showcase-heading"><?php _e( 'Recent Posts', 'newtheme' ); ?></h1>

					<?php

					// Display our recent posts, showing full content for the very latest, ignoring Aside posts.
					$recent_args = array(
						'order' => 'DESC',
						'post__not_in' => get_option( 'sticky_posts' ),
						'tax_query' => array(
							array(
								'taxonomy' => 'post_format',
								'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-quote', 'post-format-status' ),
								'field' => 'slug',
								'operator' => 'NOT IN',
							),
						),
						'no_found_rows' => true,
					);

					// Our new query for the Recent Posts section.
					$recent = new WP_Query( $recent_args );

					// The first Recent post is displayed normally
					if ( $recent->have_posts() ) : $recent->the_post();

						// Set $more to 0 in order to only get the first part of the post.
						global $more;
						$more = 0;

						get_template_part( 'content', get_post_format() );

						echo '<ol class="other-recent-posts">';

					endif;

					// For all other recent posts, just display the title and comment status.
					while ( $recent->have_posts() ) : $recent->the_post(); ?>

						<li class="entry-title">
							<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
							<span class="comments-link">
								<?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'newtheme' ) . '</span>', __( '<b>1</b> Reply', 'newtheme' ), __( '<b>%</b> Replies', 'newtheme' ) ); ?>
							</span>
						</li>

					<?php
					endwhile;

					// If we had some posts, close the <ol>
					if ( $recent->post_count > 0 )
						echo '</ol>';
					?>
				</section><!-- .recent-posts -->

				<div class="widget-area" role="complementary">
					<?php if ( ! dynamic_sidebar( 'sidebar-2' ) ) : ?>

						<?php
						the_widget( 'New_Theme_Ephemera_Widget', '', array( 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>' ) );
						?>

					<?php endif; // end sidebar widget area ?>
				</div><!-- .widget-area -->

			</div><!-- #content -->
		</div><!-- #primary -->

<?php get_footer(); ?>

[/codesyntax]

Lo primero que hace el código es indicar a WordPress que cargue el archivo showcase.js, que nosotros deberemos copiar a nuestra carpeta en la ruta correcta.

[codesyntax lang=»php»]

				<?php while ( have_posts() ) : the_post(); ?>

				<?php
					/**
					 * We are using a heading by rendering the_content
					 * If we have content for this page, let's display it.
					 */
					if ( '' != get_the_content() )
						get_template_part( 'content', 'intro' );
				?>

				<?php endwhile; ?>

[/codesyntax]

A continuación se carga el contenido de la página, normalmente una descripción, o una galería de imágenes.

[codesyntax lang=»php»]

				<?php
					/**
					 * Begin the featured posts section.
					 *
					 * See if we have any sticky posts and use them to create our featured posts.
					 * We limit the featured posts at ten.
					 */
					$sticky = get_option( 'sticky_posts' );

					// Proceed only if sticky posts exist.
					if ( ! empty( $sticky ) ) :

					$featured_args = array(
						'post__in' => $sticky,
						'post_status' => 'publish',
						'posts_per_page' => 10,
						'no_found_rows' => true,
					);

					// The Featured Posts query.
					$featured = new WP_Query( $featured_args );

					// Proceed only if published posts exist
					if ( $featured->have_posts() ) :

					/**
					 * We will need to count featured posts starting from zero
					 * to create the slider navigation.
					 */
					$counter_slider = 0;

					// Compatibility with versions of WordPress prior to 3.4.
					if ( function_exists( 'get_custom_header' ) )
						$header_image_width = get_theme_support( 'custom-header', 'width' );
					else
						$header_image_width = HEADER_IMAGE_WIDTH;
				?>

				<div class="featured-posts">
					<h1 class="showcase-heading"><?php _e( 'Featured Post', 'newtheme' ); ?></h1>

				<?php
					// Let's roll.
					while ( $featured->have_posts() ) : $featured->the_post();

					// Increase the counter.
					$counter_slider++;

					/**
					 * We're going to add a class to our featured post for featured images
					 * by default it'll have the feature-text class.
					 */
					$feature_class = 'feature-text';

					if ( has_post_thumbnail() ) {
						// ... but if it has a featured image let's add some class
						$feature_class = 'feature-image small';

						// Hang on. Let's check this here image out.
						$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( $header_image_width, $header_image_width ) );

						// Is it bigger than or equal to our header?
						if ( $image[1] >= $header_image_width ) {
							// If bigger, let's add a BIGGER class. It's EXTRA classy now.
							$feature_class = 'feature-image large';
						}
					}
					?>

					<section class="featured-post <?php echo $feature_class; ?>" id="featured-post-<?php echo $counter_slider; ?>">

						<?php
							/**
							 * If the thumbnail is as big as the header image
							 * make it a large featured post, otherwise render it small
							 */
							if ( has_post_thumbnail() ) {
								if ( $image[1] >= $header_image_width )
									$thumbnail_size = 'large-feature';
								else
									$thumbnail_size = 'small-feature';
								?>
								<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_post_thumbnail( $thumbnail_size ); ?></a>
								<?php
							}
						?>
						<?php get_template_part( 'content', 'featured' ); ?>
					</section>
				<?php endwhile;	?>

				<?php
					// Show slider only if we have more than one featured post.
					if ( $featured->post_count > 1 ) :
				?>
				<nav class="feature-slider">
					<ul>
					<?php

						// Reset the counter so that we end up with matching elements
				    	$counter_slider = 0;

						// Begin from zero
				    	rewind_posts();

						// Let's roll again.
				    	while ( $featured->have_posts() ) : $featured->the_post();
				    		$counter_slider++;
							if ( 1 == $counter_slider )
								$class = 'class="active"';
							else
								$class = '';
				    	?>
						<li><a href="#featured-post-<?php echo $counter_slider; ?>" title="<?php printf( esc_attr__( 'Featuring: %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" <?php echo $class; ?>></a></li>
					<?php endwhile;	?>
					</ul>
				</nav>
				<?php endif; // End check for more than one sticky post. ?>
				</div><!-- .featured-posts -->
				<?php endif; // End check for published posts. ?>
				<?php endif; // End check for sticky posts. ?>

[/codesyntax]

A continuación comprueba si existen post destacados para mostrar, si es así se inicia el bucle para procesar los datos y mostrar el código html correspondiente.

[codesyntax lang=»php»]

				<section class="recent-posts">
					<h1 class="showcase-heading"><?php _e( 'Recent Posts', 'newtheme' ); ?></h1>

					<?php

					// Display our recent posts, showing full content for the very latest, ignoring Aside posts.
					$recent_args = array(
						'order' => 'DESC',
						'post__not_in' => get_option( 'sticky_posts' ),
						'tax_query' => array(
							array(
								'taxonomy' => 'post_format',
								'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-quote', 'post-format-status' ),
								'field' => 'slug',
								'operator' => 'NOT IN',
							),
						),
						'no_found_rows' => true,
					);

					// Our new query for the Recent Posts section.
					$recent = new WP_Query( $recent_args );

					// The first Recent post is displayed normally
					if ( $recent->have_posts() ) : $recent->the_post();

						// Set $more to 0 in order to only get the first part of the post.
						global $more;
						$more = 0;

						get_template_part( 'content', get_post_format() );

						echo '<ol class="other-recent-posts">';

					endif;

					// For all other recent posts, just display the title and comment status.
					while ( $recent->have_posts() ) : $recent->the_post(); ?>

						<li class="entry-title">
							<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a>
							<span class="comments-link">
								<?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'newtheme' ) . '</span>', __( '<b>1</b> Reply', 'newtheme' ), __( '<b>%</b> Replies', 'newtheme' ) ); ?>
							</span>
						</li>

					<?php
					endwhile;

					// If we had some posts, close the <ol>
					if ( $recent->post_count > 0 )
						echo '</ol>';
					?>
				</section><!-- .recent-posts -->

[/codesyntax]

Después tenemos los post más recientes, que se obtienen de la misma manera que los destacados.

[codesyntax lang=»php»]

				<div class="widget-area" role="complementary">
					<?php if ( ! dynamic_sidebar( 'sidebar-2' ) ) : ?>

						<?php
						the_widget( 'New_Theme_Ephemera_Widget', '', array( 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>' ) );
						?>

					<?php endif; // end sidebar widget area ?>
				</div><!-- .widget-area -->

[/codesyntax]

Por último cargamos el widget que mostrará un listado de links a diferentes post.

 

CONTENT-INTRO.PHP

Creamos el archivo content-intro.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying page content in the showcase.php page template
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class( 'intro' ); ?>>
	<header class="entry-header">
		<h2 class="entry-title"><?php the_title(); ?></h2>
	</header><!-- .entry-header -->

	<div class="entry-content">
		<?php the_content(); ?>
		<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
		<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
	</div><!-- .entry-content -->
</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

Código sencillo, simplemente da formato al contenido.

Ir arriba