Estas en: Home > Wordpress

Entradas etiquetadas con Wordpress

Tema Mystique para WordPress provoca el error child pid XXXXX exit signal Segmentation fault (11)

0

Estoy seguro que conoceréis este tema para WordPress, el cual fue uno de los más valorados hace ya algunos años, de hecho este blog lo usa actualmente, aunque por desgracia la empresa que lo desarrolló lleva varios años sin mantenerlo, y eso provoca que aparezcan errores que antes no aparecían, por culpa de los avances en otras aplicaciones de las que depende este tema, como en nuestro caso, de PHP.

Bien, voy al grano: Hace varias semanas cambié el blog de servidor y de pronto, al entrar en un post, el blog se quedaba en blanco. No se mostraba contenido. Y en Chrome aparecía el error: ERR_INCOMPLETE_CHUNKED_ENCODING. Estoy seguro, que si te ha pasado, habrás exclamado la misma frase que yo: ¿Pero que coño es eso?.

Mirando los logs del blog, encontré el error: child pid XXXXX exit signal Segmentation fault (11), a lo que exclamé la misma expresión anterior, pero añadiendo un «¡Ostia puta!» al principio.

El segundo error es el importante. Es el que nos dice que algo se ha jodido en PHP. Pero… ¿Por qué? y lo más importante ¿El qué?.

Después de muchas pruebas, vi que el error se estaba generando en el tema Mystique, y más concretamente en la plantilla single.php.

Indagando más sobre el código conseguí llegar a la fuente del problema: cuatro putos ampersand (&) de los cojones que me han jodido un fin de semana entero con la tontería. El error es debido a la versión de PHP. En el servidor anterior era la 5.2, y en el actual es la 5.4.

 

Solución

Os explico la solución que es bastante sencillita:

En los archivos atom-core.php y AtomObjectPost.php busca la función «separate_comments», te deben aparecer dos resultados en cada archivo. Verás que delante de la función tiene un ampersand (&), elimínalo (con voz de El Padrino: «Que parezca un accidente»). Y con el resto de resultados igual. Guarda y solucionado.

Optimización de WordPress

El widget de pestañas falla en el tema Mystique 3.2.9.3 para WordPress

4

El widget de pestañas permite mostrar en un mismo espacio, lo que habitualmente tendríamos que tener en varios widgets. En este blog se muestra en la columna de la derecha, donde podéis navegar por varios elementos que os ofrecen diversa información y contenidos del blog.

Pues bien, desde hace un tiempo, vengo observando como al pulsar en las pestañas, estas, simplemente, no hacen nada: no carga otro contenido, no hay navegación, etc.

Como no quiero aburriros con el proceso de búsqueda del error, voy al grano: dentro de wp-content/themes/mystique/js hay un archivo llamado jquery.atom.js. En este archivo localizamos las siguientes líneas:

$('.sections', tabs).css('height', $("#" + $('.navi li.active a', tabs).attr('href'), tabs).outerHeight(true));

var current = $("#" + $('.navi li.active', tabs).removeClass('active').find('a').attr('href'), tabs),
next = $("#" + $(this).parent('li').addClass('active').find('a').attr('href'), tabs);

Y las sustituis por las siguientes líneas:

$('.sections', tabs).css('height', $($('.navi li.active a', tabs).attr('href'), tabs).outerHeight(true));

var current = $($('.navi li.active', tabs).removeClass('active').find('a').attr('href'), tabs),
next = $($(this).parent('li').addClass('active').find('a').attr('href'), tabs);

Como ya habrás observado solo hay que eliminar la almohadilla que hay dentro de los selectores («#» + ), que es lo que provoca que no funcionen las pestañas.

Tendrás que comprimir el archivo y llamarlo jquery.atom.min.js, para que al activar la opción de Mystique de «Optimizar el sitio web para carga rápida», no vuelva a reproducirse el fallo. También puedes modificar este archivo a mano, aunque solo te lo recomiendo si sabes lo que estas haciendo.

Cron Job WordPress

Collapsing category list: Oculta y despliega las subcategorías de WordPress

1

Durante un tiempo estuve buscando un plugin para ocultar y desplegar las categorías con subcategorías en WordPress, por desgracia los plugins que probé o no funcionaban o estaban abandonados o solo funcionaban para unos themes concretos. Así que me decidí a crear el mío: Collapsing category list, es un pequeño plugin, en realidad un filtro para las categorías por defecto de WordPress que permite colapsar y desplegar las categorías con subcategorías

Categoría colapsada

Categoría colapsada

 

Categoría desplegada

Categoría desplegada

 

Si deseas descargarlo puedes acceder por esta URL: http://wordpress.org/extend/plugins/collapsing-category-list/

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.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, content-image.php, content-link.php, content-quote.php y content-status.php

0

CONTENT-IMAGE.PHP

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

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying posts in the Image Post Format on index and archive pages
 *
 * Learn more: http://codex.wordpress.org/Post_Formats
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>
	<article id="post-<?php the_ID(); ?>" <?php post_class( 'indexed' ); ?>>
		<header class="entry-header">
			<hgroup>
				<h2 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></h2>
				<h3 class="entry-format"><?php _e( 'Image', 'newtheme' ); ?></h3>
			</hgroup>

			<?php if ( comments_open() && ! post_password_required() ) : ?>
			<div class="comments-link">
				<?php comments_popup_link( '<span class="leave-reply">' . __( "Reply", 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
			</div>
			<?php endif; ?>
		</header><!-- .entry-header -->

		<div class="entry-content">
			<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
			<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
		</div><!-- .entry-content -->

		<footer class="entry-meta">
			<div class="entry-meta">
				<?php
					printf( __( '<a href="%1$s" rel="bookmark"><time class="entry-date" datetime="%2$s" pubdate>%3$s</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="%4$s" title="%5$s" rel="author">%6$s</a></span></span>', 'newtheme' ),
						esc_url( get_permalink() ),
						get_the_date( 'c' ),
						get_the_date(),
						esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
						esc_attr( sprintf( __( 'View all posts by %s', 'newtheme' ), get_the_author() ) ),
						get_the_author()
					);
				?>
			</div><!-- .entry-meta -->
			<div class="entry-meta">
				<?php
					/* translators: used between list items, there is a space after the comma */
					$categories_list = get_the_category_list( __( ', ', 'newtheme' ) );
					if ( $categories_list ):
				?>
				<span class="cat-links">
					<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list ); ?>
				</span>
				<?php endif; // End if categories ?>
				<?php
					/* translators: used between list items, there is a space after the comma */
					$tags_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
					if ( $tags_list ): ?>
				<span class="tag-links">
					<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?>
				</span>
				<?php endif; // End if $tags_list ?>

				<?php if ( comments_open() ) : ?>
				<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>
				<?php endif; // End if comments_open() ?>
			</div><!-- .entry-meta -->

			<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
		</footer><!-- #entry-meta -->
	</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

Este tipo de contenido simplemente muestra una imagen y su respectivo título.

 

CONTENT-LINK.PHP

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

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying posts in the Link Post Format on index and archive pages
 *
 * Learn more: http://codex.wordpress.org/Post_Formats
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>

	<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
		<header class="entry-header">
			<hgroup>
				<h2 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></h2>
				<h3 class="entry-format"><?php _e( 'Link', 'newtheme' ); ?></h3>
			</hgroup>

			<?php if ( comments_open() && ! post_password_required() ) : ?>
			<div class="comments-link">
				<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
			</div>
			<?php endif; ?>
		</header><!-- .entry-header -->

		<?php if ( is_search() ) : // Only display Excerpts for Search ?>
		<div class="entry-summary">
			<?php the_excerpt(); ?>
		</div><!-- .entry-summary -->
		<?php else : ?>
		<div class="entry-content">
			<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
			<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
		</div><!-- .entry-content -->
		<?php endif; ?>

		<footer class="entry-meta">
			<?php newtheme_posted_on(); ?>
			<?php if ( comments_open() ) : ?>
			<span class="sep"> | </span>
			<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>
			<?php endif; ?>
			<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
		</footer><!-- #entry-meta -->
	</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

Este contenido es más sencillo aún. Simplemente mostramos un link o un conjunto de estos.

 

CONTENT-QUOTE.PHP

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

[codesyntax lang=»php»]

<?php

<?php
/**
 * The default template for displaying content
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>

	<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
		<header class="entry-header">
			<hgroup>
				<h2 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></h2>
				<h3 class="entry-format"><?php _e( 'Quote', 'newtheme' ); ?></h3>
			</hgroup>

			<div class="entry-meta">
				<?php newtheme_posted_on(); ?>
			</div><!-- .entry-meta -->

			<?php if ( comments_open() && ! post_password_required() ) : ?>
			<div class="comments-link">
				<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
			</div>
			<?php endif; ?>
		</header><!-- .entry-header -->

		<?php if ( is_search() ) : // Only display Excerpts for Search ?>
		<div class="entry-summary">
			<?php the_excerpt(); ?>
		</div><!-- .entry-summary -->
		<?php else : ?>
		<div class="entry-content">
			<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
			<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
		</div><!-- .entry-content -->
		<?php endif; ?>

		<footer class="entry-meta">
			<?php $show_sep = false; ?>
			<?php
				/* translators: used between list items, there is a space after the comma */
				$categories_list = get_the_category_list( __( ', ', 'newtheme' ) );
				if ( $categories_list ):
			?>
			<span class="cat-links">
				<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
				$show_sep = true; ?>
			</span>
			<?php endif; // End if categories ?>
			<?php
				/* translators: used between list items, there is a space after the comma */
				$tags_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
				if ( $tags_list ):
				if ( $show_sep ) : ?>
			<span class="sep"> | </span>
				<?php endif; // End if $show_sep ?>
			<span class="tag-links">
				<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
				$show_sep = true; ?>
			</span>
			<?php endif; // End if $tags_list ?>

			<?php if ( comments_open() ) : ?>
			<?php if ( $show_sep ) : ?>
			<span class="sep"> | </span>
			<?php endif; // End if $show_sep ?>
			<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>
			<?php endif; // End if comments_open() ?>

			<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
		</footer><!-- #entry-meta -->
	</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

Más de lo mismo, lo único que cambia es que aparece un subtítulo indicando que es una cita.

 

CONTENT-STATUS.PHP

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

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying posts in the Status Post Format on index and archive pages
 *
 * Learn more: http://codex.wordpress.org/Post_Formats
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>

	<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
		<header class="entry-header">
			<hgroup>
				<h2 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></h2>
				<h3 class="entry-format"><?php _e( 'Status', 'newtheme' ); ?></h3>
			</hgroup>

			<?php if ( comments_open() && ! post_password_required() ) : ?>
			<div class="comments-link">
				<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
			</div>
			<?php endif; ?>
		</header><!-- .entry-header -->

		<?php if ( is_search() ) : // Only display Excerpts for Search ?>
		<div class="entry-summary">
			<?php the_excerpt(); ?>
		</div><!-- .entry-summary -->
		<?php else : ?>
		<div class="entry-content">
			<div class="avatar"><?php echo get_avatar( get_the_author_meta( 'ID' ), apply_filters( 'newtheme_status_avatar', '65' ) ); ?></div>

			<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
			<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
		</div><!-- .entry-content -->
		<?php endif; ?>

		<footer class="entry-meta">
			<?php newtheme_posted_on(); ?>
			<?php if ( comments_open() ) : ?>
			<span class="sep"> | </span>
			<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>
			<?php endif; ?>
			<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
		</footer><!-- #entry-meta -->
	</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

En este caso se añade la imagen del perfil del autor o avatar para acompañar al contenido.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, content-aside.php, content-featured.php y content-gallery.php

0

Durante los próximos post, incluido este, explicaré las últimas plantillas que quedan por crear de nuestro tema, después continuaré el tutorial con los plugins.

 

CONTENT-ASIDE.PHP

WordPress dispone de varios formatos de post que pueden ser personalizados (ver: http://codex.wordpress.org/Post_Formats), entre ellos se encuentra aside, que es parecido a una actualización de Facebook, es decir, no tiene título.

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

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying posts in the Aside Post Format on index and archive pages
 *
 * Learn more: http://codex.wordpress.org/Post_Formats
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>

	<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
		<header class="entry-header">
			<hgroup>
				<h2 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></h2>
				<h3 class="entry-format"><?php _e( 'Aside', 'newtheme' ); ?></h3>
			</hgroup>

			<?php if ( comments_open() && ! post_password_required() ) : ?>
			<div class="comments-link">
				<?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
			</div>
			<?php endif; ?>
		</header><!-- .entry-header -->

		<?php if ( is_search() ) : // Only display Excerpts for Search ?>
		<div class="entry-summary">
			<?php the_excerpt(); ?>
		</div><!-- .entry-summary -->
		<?php else : ?>
		<div class="entry-content">
			<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
			<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
		</div><!-- .entry-content -->
		<?php endif; ?>

		<footer class="entry-meta">
			<?php newtheme_posted_on(); ?>
			<?php if ( comments_open() ) : ?>
			<span class="sep"> | </span>
			<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>
			<?php endif; ?>
			<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
		</footer><!-- #entry-meta -->
	</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

Como veis, lo primero que se crea es la cabecera del post, pero en este caso, en vez de mostrar el título del post se mostrará el texto «Aside«. El resto del código es prácticamente igual al de un post normal: se muestra el contenido del post y se crea el pie de este con los metadatos y los correspondientes links, entre ellos el de editar.

 

CONTENT-FEATURED.PHP

Los post featured son los post destacados de los que ya hemos hablado con anterioridad. Aunque este tipo de post no aparece en la lista de formatos de post, si es una características de los post normales que se puede personalizar con su propia plantilla.

Por tanto crearemos el archivo content-featured.php y añadiremos el siguiente código:

[codesyntax lang=»php»]

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

global $feature_class;
?>
<article id="post-<?php the_ID(); ?>" <?php post_class( $feature_class ); ?>>
	<header class="entry-header">
		<h2 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></h2>

		<div class="entry-meta">
			<?php newtheme_posted_on(); ?>
		</div><!-- .entry-meta -->
	</header><!-- .entry-header -->

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

	<footer class="entry-meta">
		<?php
			/* translators: used between list items, there is a space after the comma */
			$tag_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
			if ( '' != $tag_list ) {
				$utility_text = __( 'This entry was posted in %1$s and tagged %2$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'newtheme' );
			} else {
				$utility_text = __( 'This entry was posted in %1$s. Bookmark the <a href="%3$s" title="Permalink to %4$s" rel="bookmark">permalink</a>.', 'newtheme' );
			}
			printf(
				$utility_text,
				/* translators: used between list items, there is a space after the comma */
				get_the_category_list( __( ', ', 'newtheme' ) ),
				$tag_list,
				esc_url( get_permalink() ),
				the_title_attribute( 'echo=0' )
			);
		?>

		<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
	</footer><!-- .entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

Lo mismo de antes, se muestra el título, se muestra el contenido y se muestra el pie del post, la única diferencia sería que, en este caso también mostramos el texto «FEATURED» o «DESTACADO» en la página principal.

 

CONTENT-GALLERY.PHP

Este tipo de contenido nos permite mostrar galerías de imágenes, adjuntando las imágenes al post.

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

[codesyntax lang=»php»]

<?php
/**
 * The template for displaying posts in the Gallery Post Format on index and archive pages
 *
 * Learn more: http://codex.wordpress.org/Post_Formats
 *
 * @package WordPress
 * @subpackage New_Theme
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
	<header class="entry-header">
		<hgroup>
			<h2 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></h2>
			<h3 class="entry-format"><?php _e( 'Gallery', 'newtheme' ); ?></h3>
		</hgroup>

		<div class="entry-meta">
			<?php newtheme_posted_on(); ?>
		</div><!-- .entry-meta -->
	</header><!-- .entry-header -->

	<?php if ( is_search() ) : // Only display Excerpts for search pages ?>
		<div class="entry-summary">
			<?php the_excerpt(); ?>
		</div><!-- .entry-summary -->
		<?php else : ?>
		<div class="entry-content">
			<?php if ( post_password_required() ) : ?>
				<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>

			<?php else : ?>
				<?php
					$images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
					if ( $images ) :
						$total_images = count( $images );
						$image = array_shift( $images );
						$image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' );
				?>

				<figure class="gallery-thumb">
					<a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
				</figure><!-- .gallery-thumb -->

				<p><em><?php printf( _n( 'This gallery contains <a %1$s>%2$s photo</a>.', 'This gallery contains <a %1$s>%2$s photos</a>.', $total_images, 'newtheme' ),
						'href="' . esc_url( get_permalink() ) . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
						number_format_i18n( $total_images )
					); ?></em></p>
			<?php endif; ?>
			<?php the_excerpt(); ?>
		<?php endif; ?>
		<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
	</div><!-- .entry-content -->
	<?php endif; ?>

	<footer class="entry-meta">
		<?php $show_sep = false; ?>
		<?php
			/* translators: used between list items, there is a space after the comma */
			$categories_list = get_the_category_list( __( ', ', 'newtheme' ) );
			if ( $categories_list ):
		?>
		<span class="cat-links">
			<?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
			$show_sep = true; ?>
		</span>
		<?php endif; // End if categories ?>
		<?php
			/* translators: used between list items, there is a space after the comma */
			$tags_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
			if ( $tags_list ):
			if ( $show_sep ) : ?>
		<span class="sep"> | </span>
			<?php endif; // End if $show_sep ?>
		<span class="tag-links">
			<?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
			$show_sep = true; ?>
		</span>
		<?php endif; // End if $tags_list ?>

		<?php if ( comments_open() ) : ?>
		<?php if ( $show_sep ) : ?>
		<span class="sep"> | </span>
		<?php endif; // End if $show_sep ?>
		<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>
		<?php endif; // End if comments_open() ?>

		<?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
	</footer><!-- #entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->

[/codesyntax]

La parte más importante de este código es el siguiente extracto:

[codesyntax lang=»php»]

			<?php if ( post_password_required() ) : ?>
				<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>

			<?php else : ?>
				<?php
					$images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
					if ( $images ) :
						$total_images = count( $images );
						$image = array_shift( $images );
						$image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' );
				?>

				<figure class="gallery-thumb">
					<a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
				</figure><!-- .gallery-thumb -->

				<p><em><?php printf( _n( 'This gallery contains <a %1$s>%2$s photo</a>.', 'This gallery contains <a %1$s>%2$s photos</a>.', $total_images, 'newtheme' ),
						'href="' . esc_url( get_permalink() ) . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
						number_format_i18n( $total_images )
					); ?></em></p>
			<?php endif; ?>

[/codesyntax]

Esta parte es la que calcula el número de imágenes en el post y las convierte en una galería.

Ir arriba