El siguiente archivo que vamos a crear es widgets.php que generará un widget para mostrar diferentes tipos de contenido, como citas estados, etc.

 

WIDGETS.PHP

Creamos el archivo inc/widgets.php y añadimos el siguiente código:

[codesyntax lang=»php»]

<?php

/**
 * Makes a custom Widget for displaying Aside, Link, Status, and Quote Posts available with New Theme
 *
 * Learn more: http://codex.wordpress.org/Widgets_API#Developing_Widgets
 *
 * @package WordPress
 * @subpackage Nwe_Theme
 */
class New_Theme_Ephemera_Widget extends WP_Widget {

}

[/codesyntax]

Creamos la clase New_Theme_Ephemera_Widget que nos permitirá crear el widget.

Dentro de la clase añadimos los siguientes métodos.

[codesyntax lang=»php»]

<?php

	/**
	 * Constructor
	 *
	 * @return void
	 **/
	function New_Theme_Ephemera_Widget() {
		$widget_ops = array( 'classname' => 'widget_newtheme_ephemera', 'description' => __( 'Use this widget to list your recent Aside, Status, Quote, and Link posts', 'newtheme' ) );
		$this->WP_Widget( 'widget_newtheme_ephemera', __( 'New Theme Ephemera', 'newtheme' ), $widget_ops );
		$this->alt_option_name = 'widget_newtheme_ephemera';

		add_action( 'save_post', array(&$this, 'flush_widget_cache' ) );
		add_action( 'deleted_post', array(&$this, 'flush_widget_cache' ) );
		add_action( 'switch_theme', array(&$this, 'flush_widget_cache' ) );
	}

[/codesyntax]

Este método es el constructor del widget, le indica a WordPress la clase que utilizará, la desripción y el nombre del widget. Además se añaden varias acciones para volver a generar la cache cuando se guarde o elimine un post o cuando se cambie de tema.

[codesyntax lang=»php»]

<?php

	/**
	 * Outputs the HTML for this widget.
	 *
	 * @param array An array of standard parameters for widgets in this theme
	 * @param array An array of settings for this widget instance
	 * @return void Echoes it's output
	 **/
	function widget( $args, $instance ) {
		$cache = wp_cache_get( 'widget_newtheme_ephemera', 'widget' );

		if ( !is_array( $cache ) )
			$cache = array();

		if ( ! isset( $args['widget_id'] ) )
			$args['widget_id'] = null;

		if ( isset( $cache[$args['widget_id']] ) ) {
			echo $cache[$args['widget_id']];
			return;
		}

		ob_start();
		extract( $args, EXTR_SKIP );

		$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Ephemera', 'newtheme' ) : $instance['title'], $instance, $this->id_base);

		if ( ! isset( $instance['number'] ) )
			$instance['number'] = '10';

		if ( ! $number = absint( $instance['number'] ) )
 			$number = 10;

		$ephemera_args = array(
			'order' => 'DESC',
			'posts_per_page' => $number,
			'no_found_rows' => true,
			'post_status' => 'publish',
			'post__not_in' => get_option( 'sticky_posts' ),
			'tax_query' => array(
				array(
					'taxonomy' => 'post_format',
					'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-status', 'post-format-quote' ),
					'field' => 'slug',
					'operator' => 'IN',
				),
			),
		);
		$ephemera = new WP_Query( $ephemera_args );

		if ( $ephemera->have_posts() ) :
			echo $before_widget;
			echo $before_title;
			echo $title; // Can set this with a widget option, or omit altogether
			echo $after_title;
			?>
			<ol>
			<?php while ( $ephemera->have_posts() ) : $ephemera->the_post(); ?>

				<?php if ( 'link' != get_post_format() ) : ?>

				<li class="widget-entry-title">
					<a href="<?php echo esc_url( get_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( __( '0 <span class="reply">comments &rarr;</span>', 'newtheme' ), __( '1 <span class="reply">comment &rarr;</span>', 'newtheme' ), __( '% <span class="reply">comments &rarr;</span>', 'newtheme' ) ); ?>
					</span>
				</li>

				<?php else : ?>

				<li class="widget-entry-title">
					<?php
						// Grab first link from the post content. If none found, use the post permalink as fallback.
						$link_url = newtheme_url_grabber();

						if ( empty( $link_url ) )
							$link_url = get_permalink();
					?>
					<a href="<?php echo esc_url( $link_url ); ?>" title="<?php printf( esc_attr__( 'Link to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?>&nbsp;<span>&rarr;</span></a>
					<span class="comments-link">
						<?php comments_popup_link( __( '0 <span class="reply">comments &rarr;</span>', 'newtheme' ), __( '1 <span class="reply">comment &rarr;</span>', 'newtheme' ), __( '% <span class="reply">comments &rarr;</span>', 'newtheme' ) ); ?>
					</span>
				</li>

				<?php endif; ?>

			<?php endwhile; ?>
			</ol>
			<?php

			echo $after_widget;

			// Reset the post globals as this query will have stomped on it
			wp_reset_postdata();

		// end check for ephemeral posts
		endif;

		$cache[$args['widget_id']] = ob_get_flush();
		wp_cache_set( 'widget_newtheme_ephemera', $cache, 'widget' );
	}

[/codesyntax]

Este método es un poco largo, así que voy a dividirlo y explicar el código.

[codesyntax lang=»php»]

<?php

		$cache = wp_cache_get( 'widget_newtheme_ephemera', 'widget' );

		if ( !is_array( $cache ) )
			$cache = array();

		if ( ! isset( $args['widget_id'] ) )
			$args['widget_id'] = null;

		if ( isset( $cache[$args['widget_id']] ) ) {
			echo $cache[$args['widget_id']];
			return;
		}

[/codesyntax]

Primero recuperamos los datos del widget desde la caché de WordPress.

Comprobamos que en caso de que no sea un array le damos el valor de un array vacío.

Comprobamos también que $args[‘widget_id’] no esta establecido y le damos el valor null.

Por último comprobamos que la caché disponga de algún contenido para el widget, si es así se muestra ese contenido y se devuelve un return para que php no siga ejecutando el método.

[codesyntax lang=»php»]

<?php

		ob_start();
		extract( $args, EXTR_SKIP );

		$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Ephemera', 'newtheme' ) : $instance['title'], $instance, $this->id_base);

		if ( ! isset( $instance['number'] ) )
			$instance['number'] = '10';

		if ( ! $number = absint( $instance['number'] ) )
 			$number = 10;

		$ephemera_args = array(
			'order' => 'DESC',
			'posts_per_page' => $number,
			'no_found_rows' => true,
			'post_status' => 'publish',
			'post__not_in' => get_option( 'sticky_posts' ),
			'tax_query' => array(
				array(
					'taxonomy' => 'post_format',
					'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-status', 'post-format-quote' ),
					'field' => 'slug',
					'operator' => 'IN',
				),
			),
		);
		$ephemera = new WP_Query( $ephemera_args );

[/codesyntax]

En el caso de que no haya contenido en la caché de WordPress, el método continuará ejecutandose.

En este extracto de código vemos como primero se abre el buffer de php utilizando la función ob_start(). Esta función permite que en vez de mostrar cualquier contenido que le siguiente, lo almacena en buffer para después poder mostrarlo donde corresponda con ob_get_flush().

A continuación se recupera el título y el número de post a mostrar.

Se crea un array con los parámetros para ejecutar una consulta SQL.

Por último se crea una nueva instancia de WP_Query() que devolverá los registros encontrados en la base de datos.

[codesyntax lang=»php»]

<?php

		if ( $ephemera->have_posts() ) :
			echo $before_widget;
			echo $before_title;
			echo $title; // Can set this with a widget option, or omit altogether
			echo $after_title;
			?>
			<ol>
			<?php while ( $ephemera->have_posts() ) : $ephemera->the_post(); ?>

				<?php if ( 'link' != get_post_format() ) : ?>

				<li class="widget-entry-title">
					<a href="<?php echo esc_url( get_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( __( '0 <span class="reply">comments &rarr;</span>', 'newtheme' ), __( '1 <span class="reply">comment &rarr;</span>', 'newtheme' ), __( '% <span class="reply">comments &rarr;</span>', 'newtheme' ) ); ?>
					</span>
				</li>

				<?php else : ?>

				<li class="widget-entry-title">
					<?php
						// Grab first link from the post content. If none found, use the post permalink as fallback.
						$link_url = newtheme_url_grabber();

						if ( empty( $link_url ) )
							$link_url = get_permalink();
					?>
					<a href="<?php echo esc_url( $link_url ); ?>" title="<?php printf( esc_attr__( 'Link to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?>&nbsp;<span>&rarr;</span></a>
					<span class="comments-link">
						<?php comments_popup_link( __( '0 <span class="reply">comments &rarr;</span>', 'newtheme' ), __( '1 <span class="reply">comment &rarr;</span>', 'newtheme' ), __( '% <span class="reply">comments &rarr;</span>', 'newtheme' ) ); ?>
					</span>
				</li>

				<?php endif; ?>

			<?php endwhile; ?>
			</ol>
			<?php

			echo $after_widget;

			// Reset the post globals as this query will have stomped on it
			wp_reset_postdata();

		// end check for ephemeral posts
		endif;

[/codesyntax]

Se comprueba si existen post para mostrar y si es que sí se muestran diferentes valores antes de iniciar el búcle que dará formato al contenido.

Se muestra cualquier contenido posterior al widget, se reincian los post globales que esta consulta haya podido pisar.

[codesyntax lang=»php»]

<?php

		$cache[$args['widget_id']] = ob_get_flush();
		wp_cache_set( 'widget_newtheme_ephemera', $cache, 'widget' );

[/codesyntax]

Por último se guardan los datos del buffer en la caché de WordPress.

[codesyntax lang=»php»]

<?php

	/**
	 * Deals with the settings when they are saved by the admin. Here is
	 * where any validation should be dealt with.
	 **/
	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['number'] = (int) $new_instance['number'];
		$this->flush_widget_cache();

		$alloptions = wp_cache_get( 'alloptions', 'options' );
		if ( isset( $alloptions['widget_newtheme_ephemera'] ) )
			delete_option( 'widget_newtheme_ephemera' );

		return $instance;
	}

[/codesyntax]

Este método permite verificar que los datos que ha introducido el administrador sean correctos y se guarden en la caché para futuros usos.

[codesyntax lang=»php»]

<?php

	function flush_widget_cache() {
		wp_cache_delete( 'widget_newtheme_ephemera', 'widget' );
	}

[/codesyntax]

Este método elimina el widget de la caché de WordPress.

[codesyntax lang=»php»]

<?php

	/**
	 * Displays the form for this widget on the Widgets page of the WP Admin area.
	 **/
	function form( $instance ) {
		$title = isset( $instance['title']) ? esc_attr( $instance['title'] ) : '';
		$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 10;
?>
			<p><label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Title:', 'newtheme' ); ?></label>
			<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></p>

			<p><label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>"><?php _e( 'Number of posts to show:', 'newtheme' ); ?></label>
			<input id="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'number' ) ); ?>" type="text" value="<?php echo esc_attr( $number ); ?>" size="3" /></p>
		<?php
	}

[/codesyntax]

Este último método crea el formulario donde el administrador podrá modificar el widget.