Estas en: Home > plantilla

Entradas etiquetadas con plantilla

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:

  1. <?php
  2. /**
  3.  * The template for displaying Category Archive pages.
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8.  
  9. get_header(); ?>
  10.  
  11. <section id="primary">
  12. <div id="content" role="main">
  13.  
  14. <?php if ( have_posts() ) : ?>
  15.  
  16. <header class="page-header">
  17. <h1 class="page-title"><?php
  18. printf( __( 'Category Archives: %s', 'newtheme' ), '<span>' . single_cat_title( '', false ) . '</span>' );
  19. ?></h1>
  20.  
  21. <?php
  22. $category_description = category_description();
  23. if ( ! empty( $category_description ) )
  24. echo apply_filters( 'category_archive_meta', '<div class="category-archive-meta">' . $category_description . '</div>' );
  25. ?>
  26. </header>
  27.  
  28. <?php newtheme_content_nav( 'nav-above' ); ?>
  29.  
  30. <?php /* Start the Loop */ ?>
  31. <?php while ( have_posts() ) : the_post(); ?>
  32.  
  33. <?php
  34. /* Include the Post-Format-specific template for the content.
  35. * If you want to overload this in a child theme then include a file
  36. * called content-___.php (where ___ is the Post Format name) and that will be used instead.
  37. */
  38. get_template_part( 'content', get_post_format() );
  39. ?>
  40.  
  41. <?php endwhile; ?>
  42.  
  43. <?php newtheme_content_nav( 'nav-below' ); ?>
  44.  
  45. <?php else : ?>
  46.  
  47. <article id="post-0" class="post no-results not-found">
  48. <header class="entry-header">
  49. <h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
  50. </header><!-- .entry-header -->
  51.  
  52. <div class="entry-content">
  53. <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
  54. <?php get_search_form(); ?>
  55. </div><!-- .entry-content -->
  56. </article><!-- #post-0 -->
  57.  
  58. <?php endif; ?>
  59.  
  60. </div><!-- #content -->
  61. </section><!-- #primary -->
  62.  
  63. <?php get_sidebar(); ?>
  64. <?php get_footer(); ?>

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:

  1. <?php
  2. /**
  3.  * The template for displaying Author Archive pages.
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8.  
  9. get_header(); ?>
  10.  
  11. <section id="primary">
  12. <div id="content" role="main">
  13.  
  14. <?php if ( have_posts() ) : ?>
  15.  
  16. <?php
  17. /* Queue the first post, that way we know
  18. * what author we're dealing with (if that is the case).
  19. *
  20. * We reset this later so we can run the loop
  21. * properly with a call to rewind_posts().
  22. */
  23. the_post();
  24. ?>
  25.  
  26. <header class="page-header">
  27. <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>
  28. </header>
  29.  
  30. <?php
  31. /* Since we called the_post() above, we need to
  32. * rewind the loop back to the beginning that way
  33. * we can run the loop properly, in full.
  34. */
  35. rewind_posts();
  36. ?>
  37.  
  38. <?php newtheme_content_nav( 'nav-above' ); ?>
  39.  
  40. <?php
  41. // If a user has filled out their description, show a bio on their entries.
  42. if ( get_the_author_meta( 'description' ) ) : ?>
  43. <div id="author-info">
  44. <div id="author-avatar">
  45. <?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'newtheme_author_bio_avatar_size', 60 ) ); ?>
  46. </div><!-- #author-avatar -->
  47. <div id="author-description">
  48. <h2><?php printf( __( 'About %s', 'newtheme' ), get_the_author() ); ?></h2>
  49. <?php the_author_meta( 'description' ); ?>
  50. </div><!-- #author-description -->
  51. </div><!-- #author-info -->
  52. <?php endif; ?>
  53.  
  54. <?php /* Start the Loop */ ?>
  55. <?php while ( have_posts() ) : the_post(); ?>
  56.  
  57. <?php
  58. /* Include the Post-Format-specific template for the content.
  59. * If you want to overload this in a child theme then include a file
  60. * called content-___.php (where ___ is the Post Format name) and that will be used instead.
  61. */
  62. get_template_part( 'content', get_post_format() );
  63. ?>
  64.  
  65. <?php endwhile; ?>
  66.  
  67. <?php newtheme_content_nav( 'nav-below' ); ?>
  68.  
  69. <?php else : ?>
  70.  
  71. <article id="post-0" class="post no-results not-found">
  72. <header class="entry-header">
  73. <h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
  74. </header><!-- .entry-header -->
  75.  
  76. <div class="entry-content">
  77. <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
  78. <?php get_search_form(); ?>
  79. </div><!-- .entry-content -->
  80. </article><!-- #post-0 -->
  81.  
  82. <?php endif; ?>
  83.  
  84. </div><!-- #content -->
  85. </section><!-- #primary -->
  86.  
  87. <?php get_sidebar(); ?>
  88. <?php get_footer(); ?>

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:

  1. <?php
  2. /**
  3.  * The template for displaying Archive pages.
  4.  *
  5.  * Used to display archive-type pages if nothing more specific matches a query.
  6.  * For example, puts together date-based pages if no date.php file exists.
  7.  *
  8.  * Learn more: http://codex.wordpress.org/Template_Hierarchy
  9.  *
  10.  * @package WordPress
  11.  * @subpackage Twenty_Eleven
  12.  */
  13.  
  14. get_header(); ?>
  15.  
  16. <section id="primary">
  17. <div id="content" role="main">
  18.  
  19. <?php if ( have_posts() ) : ?>
  20.  
  21. <header class="page-header">
  22. <h1 class="page-title">
  23. <?php if ( is_day() ) : ?>
  24. <?php printf( __( 'Daily Archives: %s', 'newtheme' ), '<span>' . get_the_date() . '</span>' ); ?>
  25. <?php elseif ( is_month() ) : ?>
  26. <?php printf( __( 'Monthly Archives: %s', 'newtheme' ), '<span>' . get_the_date( _x( 'F Y', 'monthly archives date format', 'newtheme' ) ) . '</span>' ); ?>
  27. <?php elseif ( is_year() ) : ?>
  28. <?php printf( __( 'Yearly Archives: %s', 'newtheme' ), '<span>' . get_the_date( _x( 'Y', 'yearly archives date format', 'newtheme' ) ) . '</span>' ); ?>
  29. <?php else : ?>
  30. <?php _e( 'Blog Archives', 'newtheme' ); ?>
  31. <?php endif; ?>
  32. </h1>
  33. </header>
  34.  
  35. <?php newtheme_content_nav( 'nav-above' ); ?>
  36.  
  37. <?php /* Start the Loop */ ?>
  38. <?php while ( have_posts() ) : the_post(); ?>
  39.  
  40. <?php
  41. /* Include the Post-Format-specific template for the content.
  42. * If you want to overload this in a child theme then include a file
  43. * called content-___.php (where ___ is the Post Format name) and that will be used instead.
  44. */
  45. get_template_part( 'content', get_post_format() );
  46. ?>
  47.  
  48. <?php endwhile; ?>
  49.  
  50. <?php newtheme_content_nav( 'nav-below' ); ?>
  51.  
  52. <?php else : ?>
  53.  
  54. <article id="post-0" class="post no-results not-found">
  55. <header class="entry-header">
  56. <h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
  57. </header><!-- .entry-header -->
  58.  
  59. <div class="entry-content">
  60. <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
  61. <?php get_search_form(); ?>
  62. </div><!-- .entry-content -->
  63. </article><!-- #post-0 -->
  64.  
  65. <?php endif; ?>
  66.  
  67. </div><!-- #content -->
  68. </section><!-- #primary -->
  69.  
  70. <?php get_sidebar(); ?>
  71. <?php get_footer(); ?>

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:

  1. <?php
  2. /**
  3.  * The template used to display Tag Archive pages
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8.  
  9. get_header(); ?>
  10.  
  11. <section id="primary">
  12. <div id="content" role="main">
  13.  
  14. <?php if ( have_posts() ) : ?>
  15.  
  16. <header class="page-header">
  17. <h1 class="page-title"><?php
  18. printf( __( 'Tag Archives: %s', 'newtheme' ), '<span>' . single_tag_title( '', false ) . '</span>' );
  19. ?></h1>
  20.  
  21. <?php
  22. $tag_description = tag_description();
  23. if ( ! empty( $tag_description ) )
  24. echo apply_filters( 'tag_archive_meta', '<div class="tag-archive-meta">' . $tag_description . '</div>' );
  25. ?>
  26. </header>
  27.  
  28. <?php newtheme_content_nav( 'nav-above' ); ?>
  29.  
  30. <?php /* Start the Loop */ ?>
  31. <?php while ( have_posts() ) : the_post(); ?>
  32.  
  33. <?php
  34. /* Include the Post-Format-specific template for the content.
  35. * If you want to overload this in a child theme then include a file
  36. * called content-___.php (where ___ is the Post Format name) and that will be used instead.
  37. */
  38. get_template_part( 'content', get_post_format() );
  39. ?>
  40.  
  41. <?php endwhile; ?>
  42.  
  43. <?php newtheme_content_nav( 'nav-below' ); ?>
  44.  
  45. <?php else : ?>
  46.  
  47. <article id="post-0" class="post no-results not-found">
  48. <header class="entry-header">
  49. <h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
  50. </header><!-- .entry-header -->
  51.  
  52. <div class="entry-content">
  53. <p><?php _e( 'Apologies, but no results were found for the requested archive. Perhaps searching will help find a related post.', 'newtheme' ); ?></p>
  54. <?php get_search_form(); ?>
  55. </div><!-- .entry-content -->
  56. </article><!-- #post-0 -->
  57.  
  58. <?php endif; ?>
  59.  
  60. </div><!-- #content -->
  61. </section><!-- #primary -->
  62.  
  63. <?php get_sidebar(); ?>
  64. <?php get_footer(); ?>

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:

  1. <?php
  2. /**
  3.  * The template for displaying Search Results pages.
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8.  
  9. get_header(); ?>
  10.  
  11. <section id="primary">
  12. <div id="content" role="main">
  13.  
  14. <?php if ( have_posts() ) : ?>
  15.  
  16. <header class="page-header">
  17. <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'newtheme' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
  18. </header>
  19.  
  20. <?php newtheme_content_nav( 'nav-above' ); ?>
  21.  
  22. <?php /* Start the Loop */ ?>
  23. <?php while ( have_posts() ) : the_post(); ?>
  24.  
  25. <?php
  26. /* Include the Post-Format-specific template for the content.
  27. * If you want to overload this in a child theme then include a file
  28. * called content-___.php (where ___ is the Post Format name) and that will be used instead.
  29. */
  30. get_template_part( 'content', get_post_format() );
  31. ?>
  32.  
  33. <?php endwhile; ?>
  34.  
  35. <?php newtheme_content_nav( 'nav-below' ); ?>
  36.  
  37. <?php else : ?>
  38.  
  39. <article id="post-0" class="post no-results not-found">
  40. <header class="entry-header">
  41. <h1 class="entry-title"><?php _e( 'Nothing Found', 'newtheme' ); ?></h1>
  42. </header><!-- .entry-header -->
  43.  
  44. <div class="entry-content">
  45. <p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'newtheme' ); ?></p>
  46. <?php get_search_form(); ?>
  47. </div><!-- .entry-content -->
  48. </article><!-- #post-0 -->
  49.  
  50. <?php endif; ?>
  51.  
  52. </div><!-- #content -->
  53. </section><!-- #primary -->
  54.  
  55. <?php get_sidebar(); ?>
  56. <?php get_footer(); ?>

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:

  1. <?php
  2. /**
  3.  * The template for displaying search forms in Twenty Eleven
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8. ?>
  9. <form method="get" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
  10. <label for="s" class="assistive-text"><?php _e( 'Search', 'newtheme' ); ?></label>
  11. <input type="text" class="field" name="s" id="s" placeholder="<?php esc_attr_e( 'Search', 'newtheme' ); ?>" />
  12. <input type="submit" class="submit" name="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search', 'newtheme' ); ?>" />
  13. </form>

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:

  1. <?php
  2. /**
  3.  * The template for displaying image attachments.
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8.  
  9. get_header(); ?>
  10.  
  11. <div id="primary" class="image-attachment">
  12. <div id="content" role="main">
  13.  
  14. <?php while ( have_posts() ) : the_post(); ?>
  15.  
  16. <nav id="nav-single">
  17. <h3 class="assistive-text"><?php _e( 'Image navigation', 'newtheme' ); ?></h3>
  18. <span class="nav-previous"><?php previous_image_link( false, __( '&larr; Previous' , 'newtheme' ) ); ?></span>
  19. <span class="nav-next"><?php next_image_link( false, __( 'Next &rarr;' , 'newtheme' ) ); ?></span>
  20. </nav><!-- #nav-single -->
  21.  
  22. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  23. <header class="entry-header">
  24. <h1 class="entry-title"><?php the_title(); ?></h1>
  25.  
  26. <div class="entry-meta">
  27. <?php
  28. $metadata = wp_get_attachment_metadata();
  29. 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' ),
  30. esc_attr( get_the_time() ),
  31. get_the_date(),
  32. esc_url( wp_get_attachment_url() ),
  33. $metadata['width'],
  34. $metadata['height'],
  35. esc_url( get_permalink( $post->post_parent ) ),
  36. esc_attr( strip_tags( get_the_title( $post->post_parent ) ) ),
  37. get_the_title( $post->post_parent )
  38. );
  39. ?>
  40. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  41. </div><!-- .entry-meta -->
  42.  
  43. </header><!-- .entry-header -->
  44.  
  45. <div class="entry-content">
  46.  
  47. <div class="entry-attachment">
  48. <div class="attachment">
  49. <?php
  50. /**
  51. * 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,
  52. * 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
  53. */
  54. $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' ) ) );
  55. foreach ( $attachments as $k => $attachment ) {
  56. if ( $attachment->ID == $post->ID )
  57. break;
  58. }
  59. $k++;
  60. // If there is more than 1 attachment in a gallery
  61. if ( count( $attachments ) > 1 ) {
  62. if ( isset( $attachments[ $k ] ) )
  63. // get the URL of the next image attachment
  64. $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID );
  65. else
  66. // or get the URL of the first image attachment
  67. $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID );
  68. } else {
  69. // or, if there's only 1 image, get the URL of the image
  70. $next_attachment_url = wp_get_attachment_url();
  71. }
  72. ?>
  73. <a href="<?php echo esc_url( $next_attachment_url ); ?>" title="<?php the_title_attribute(); ?>" rel="attachment"><?php
  74. $attachment_size = apply_filters( 'newtheme_attachment_size', 848 );
  75. echo wp_get_attachment_image( $post->ID, array( $attachment_size, 1024 ) ); // filterable image width with 1024px limit for image height.
  76. ?></a>
  77.  
  78. <?php if ( ! empty( $post->post_excerpt ) ) : ?>
  79. <div class="entry-caption">
  80. <?php the_excerpt(); ?>
  81. </div>
  82. <?php endif; ?>
  83. </div><!-- .attachment -->
  84.  
  85. </div><!-- .entry-attachment -->
  86.  
  87. <div class="entry-description">
  88. <?php the_content(); ?>
  89. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  90. </div><!-- .entry-description -->
  91.  
  92. </div><!-- .entry-content -->
  93.  
  94. </article><!-- #post-<?php the_ID(); ?> -->
  95.  
  96. <?php comments_template(); ?>
  97.  
  98. <?php endwhile; // end of the loop. ?>
  99.  
  100. </div><!-- #content -->
  101. </div><!-- #primary -->
  102.  
  103. <?php get_footer(); ?>

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:

  1. <?php
  2. /**
  3.  * Template Name: Showcase Template
  4.  * Description: A Page Template that showcases Sticky Posts, Asides, and Blog Posts
  5.  *
  6.  * The showcase template in New Theme consists of a featured posts section using sticky posts,
  7.  * another recent posts area (with the latest post shown in full and the rest as a list)
  8.  * and a left sidebar holding aside posts.
  9.  *
  10.  * We are creating two queries to fetch the proper posts and a custom widget for the sidebar.
  11.  *
  12.  * @package WordPress
  13.  * @subpackage New_Theme
  14.  */
  15.  
  16. // Enqueue showcase script for the slider
  17. wp_enqueue_script( 'newtheme-showcase', get_template_directory_uri() . '/js/showcase.js', array( 'jquery' ), '2011-04-28' );
  18.  
  19. get_header(); ?>
  20.  
  21. <div id="primary" class="showcase">
  22. <div id="content" role="main">
  23.  
  24. <?php while ( have_posts() ) : the_post(); ?>
  25.  
  26. <?php
  27. /**
  28. * We are using a heading by rendering the_content
  29. * If we have content for this page, let's display it.
  30. */
  31. if ( '' != get_the_content() )
  32. get_template_part( 'content', 'intro' );
  33. ?>
  34.  
  35. <?php endwhile; ?>
  36.  
  37. <?php
  38. /**
  39. * Begin the featured posts section.
  40. *
  41. * See if we have any sticky posts and use them to create our featured posts.
  42. * We limit the featured posts at ten.
  43. */
  44. $sticky = get_option( 'sticky_posts' );
  45.  
  46. // Proceed only if sticky posts exist.
  47. if ( ! empty( $sticky ) ) :
  48.  
  49. $featured_args = array(
  50. 'post__in' => $sticky,
  51. 'post_status' => 'publish',
  52. 'posts_per_page' => 10,
  53. 'no_found_rows' => true,
  54. );
  55.  
  56. // The Featured Posts query.
  57. $featured = new WP_Query( $featured_args );
  58.  
  59. // Proceed only if published posts exist
  60. if ( $featured->have_posts() ) :
  61.  
  62. /**
  63. * We will need to count featured posts starting from zero
  64. * to create the slider navigation.
  65. */
  66. $counter_slider = 0;
  67.  
  68. // Compatibility with versions of WordPress prior to 3.4.
  69. if ( function_exists( 'get_custom_header' ) )
  70. $header_image_width = get_theme_support( 'custom-header', 'width' );
  71. else
  72. $header_image_width = HEADER_IMAGE_WIDTH;
  73. ?>
  74.  
  75. <div class="featured-posts">
  76. <h1 class="showcase-heading"><?php _e( 'Featured Post', 'newtheme' ); ?></h1>
  77.  
  78. <?php
  79. // Let's roll.
  80. while ( $featured->have_posts() ) : $featured->the_post();
  81.  
  82. // Increase the counter.
  83. $counter_slider++;
  84.  
  85. /**
  86. * We're going to add a class to our featured post for featured images
  87. * by default it'll have the feature-text class.
  88. */
  89. $feature_class = 'feature-text';
  90.  
  91. if ( has_post_thumbnail() ) {
  92. // ... but if it has a featured image let's add some class
  93. $feature_class = 'feature-image small';
  94.  
  95. // Hang on. Let's check this here image out.
  96. $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( $header_image_width, $header_image_width ) );
  97.  
  98. // Is it bigger than or equal to our header?
  99. if ( $image[1] >= $header_image_width ) {
  100. // If bigger, let's add a BIGGER class. It's EXTRA classy now.
  101. $feature_class = 'feature-image large';
  102. }
  103. }
  104. ?>
  105.  
  106. <section class="featured-post <?php echo $feature_class; ?>" id="featured-post-<?php echo $counter_slider; ?>">
  107.  
  108. <?php
  109. /**
  110. * If the thumbnail is as big as the header image
  111. * make it a large featured post, otherwise render it small
  112. */
  113. if ( has_post_thumbnail() ) {
  114. if ( $image[1] >= $header_image_width )
  115. $thumbnail_size = 'large-feature';
  116. else
  117. $thumbnail_size = 'small-feature';
  118. ?>
  119. <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>
  120. <?php
  121. }
  122. ?>
  123. <?php get_template_part( 'content', 'featured' ); ?>
  124. </section>
  125. <?php endwhile; ?>
  126.  
  127. <?php
  128. // Show slider only if we have more than one featured post.
  129. if ( $featured->post_count > 1 ) :
  130. ?>
  131. <nav class="feature-slider">
  132. <ul>
  133. <?php
  134.  
  135. // Reset the counter so that we end up with matching elements
  136. $counter_slider = 0;
  137.  
  138. // Begin from zero
  139. rewind_posts();
  140.  
  141. // Let's roll again.
  142. while ( $featured->have_posts() ) : $featured->the_post();
  143. $counter_slider++;
  144. if ( 1 == $counter_slider )
  145. $class = 'class="active"';
  146. else
  147. $class = '';
  148. ?>
  149. <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>
  150. <?php endwhile; ?>
  151. </ul>
  152. </nav>
  153. <?php endif; // End check for more than one sticky post. ?>
  154. </div><!-- .featured-posts -->
  155. <?php endif; // End check for published posts. ?>
  156. <?php endif; // End check for sticky posts. ?>
  157.  
  158. <section class="recent-posts">
  159. <h1 class="showcase-heading"><?php _e( 'Recent Posts', 'newtheme' ); ?></h1>
  160.  
  161. <?php
  162.  
  163. // Display our recent posts, showing full content for the very latest, ignoring Aside posts.
  164. $recent_args = array(
  165. 'order' => 'DESC',
  166. 'post__not_in' => get_option( 'sticky_posts' ),
  167. 'tax_query' => array(
  168. 'taxonomy' => 'post_format',
  169. 'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-quote', 'post-format-status' ),
  170. 'field' => 'slug',
  171. 'operator' => 'NOT IN',
  172. ),
  173. ),
  174. 'no_found_rows' => true,
  175. );
  176.  
  177. // Our new query for the Recent Posts section.
  178. $recent = new WP_Query( $recent_args );
  179.  
  180. // The first Recent post is displayed normally
  181. if ( $recent->have_posts() ) : $recent->the_post();
  182.  
  183. // Set $more to 0 in order to only get the first part of the post.
  184. global $more;
  185. $more = 0;
  186.  
  187. get_template_part( 'content', get_post_format() );
  188.  
  189. echo '<ol class="other-recent-posts">';
  190.  
  191. endif;
  192.  
  193. // For all other recent posts, just display the title and comment status.
  194. while ( $recent->have_posts() ) : $recent->the_post(); ?>
  195.  
  196. <li class="entry-title">
  197. <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>
  198. <span class="comments-link">
  199. <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'newtheme' ) . '</span>', __( '<b>1</b> Reply', 'newtheme' ), __( '<b>%</b> Replies', 'newtheme' ) ); ?>
  200. </span>
  201. </li>
  202.  
  203. <?php
  204. endwhile;
  205.  
  206. // If we had some posts, close the <ol>
  207. if ( $recent->post_count > 0 )
  208. echo '</ol>';
  209. ?>
  210. </section><!-- .recent-posts -->
  211.  
  212. <div class="widget-area" role="complementary">
  213. <?php if ( ! dynamic_sidebar( 'sidebar-2' ) ) : ?>
  214.  
  215. <?php
  216. the_widget( 'New_Theme_Ephemera_Widget', '', array( 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>' ) );
  217. ?>
  218.  
  219. <?php endif; // end sidebar widget area ?>
  220. </div><!-- .widget-area -->
  221.  
  222. </div><!-- #content -->
  223. </div><!-- #primary -->
  224.  
  225. <?php get_footer(); ?>

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.

  1. <?php while ( have_posts() ) : the_post(); ?>
  2.  
  3. <?php
  4. /**
  5. * We are using a heading by rendering the_content
  6. * If we have content for this page, let's display it.
  7. */
  8. if ( '' != get_the_content() )
  9. get_template_part( 'content', 'intro' );
  10. ?>
  11.  
  12. <?php endwhile; ?>

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

  1. <?php
  2. /**
  3. * Begin the featured posts section.
  4. *
  5. * See if we have any sticky posts and use them to create our featured posts.
  6. * We limit the featured posts at ten.
  7. */
  8. $sticky = get_option( 'sticky_posts' );
  9.  
  10. // Proceed only if sticky posts exist.
  11. if ( ! empty( $sticky ) ) :
  12.  
  13. $featured_args = array(
  14. 'post__in' => $sticky,
  15. 'post_status' => 'publish',
  16. 'posts_per_page' => 10,
  17. 'no_found_rows' => true,
  18. );
  19.  
  20. // The Featured Posts query.
  21. $featured = new WP_Query( $featured_args );
  22.  
  23. // Proceed only if published posts exist
  24. if ( $featured->have_posts() ) :
  25.  
  26. /**
  27. * We will need to count featured posts starting from zero
  28. * to create the slider navigation.
  29. */
  30. $counter_slider = 0;
  31.  
  32. // Compatibility with versions of WordPress prior to 3.4.
  33. if ( function_exists( 'get_custom_header' ) )
  34. $header_image_width = get_theme_support( 'custom-header', 'width' );
  35. else
  36. $header_image_width = HEADER_IMAGE_WIDTH;
  37. ?>
  38.  
  39. <div class="featured-posts">
  40. <h1 class="showcase-heading"><?php _e( 'Featured Post', 'newtheme' ); ?></h1>
  41.  
  42. <?php
  43. // Let's roll.
  44. while ( $featured->have_posts() ) : $featured->the_post();
  45.  
  46. // Increase the counter.
  47. $counter_slider++;
  48.  
  49. /**
  50. * We're going to add a class to our featured post for featured images
  51. * by default it'll have the feature-text class.
  52. */
  53. $feature_class = 'feature-text';
  54.  
  55. if ( has_post_thumbnail() ) {
  56. // ... but if it has a featured image let's add some class
  57. $feature_class = 'feature-image small';
  58.  
  59. // Hang on. Let's check this here image out.
  60. $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( $header_image_width, $header_image_width ) );
  61.  
  62. // Is it bigger than or equal to our header?
  63. if ( $image[1] >= $header_image_width ) {
  64. // If bigger, let's add a BIGGER class. It's EXTRA classy now.
  65. $feature_class = 'feature-image large';
  66. }
  67. }
  68. ?>
  69.  
  70. <section class="featured-post <?php echo $feature_class; ?>" id="featured-post-<?php echo $counter_slider; ?>">
  71.  
  72. <?php
  73. /**
  74. * If the thumbnail is as big as the header image
  75. * make it a large featured post, otherwise render it small
  76. */
  77. if ( has_post_thumbnail() ) {
  78. if ( $image[1] >= $header_image_width )
  79. $thumbnail_size = 'large-feature';
  80. else
  81. $thumbnail_size = 'small-feature';
  82. ?>
  83. <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>
  84. <?php
  85. }
  86. ?>
  87. <?php get_template_part( 'content', 'featured' ); ?>
  88. </section>
  89. <?php endwhile; ?>
  90.  
  91. <?php
  92. // Show slider only if we have more than one featured post.
  93. if ( $featured->post_count > 1 ) :
  94. ?>
  95. <nav class="feature-slider">
  96. <ul>
  97. <?php
  98.  
  99. // Reset the counter so that we end up with matching elements
  100. $counter_slider = 0;
  101.  
  102. // Begin from zero
  103. rewind_posts();
  104.  
  105. // Let's roll again.
  106. while ( $featured->have_posts() ) : $featured->the_post();
  107. $counter_slider++;
  108. if ( 1 == $counter_slider )
  109. $class = 'class="active"';
  110. else
  111. $class = '';
  112. ?>
  113. <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>
  114. <?php endwhile; ?>
  115. </ul>
  116. </nav>
  117. <?php endif; // End check for more than one sticky post. ?>
  118. </div><!-- .featured-posts -->
  119. <?php endif; // End check for published posts. ?>
  120. <?php endif; // End check for sticky posts. ?>

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.

  1. <section class="recent-posts">
  2. <h1 class="showcase-heading"><?php _e( 'Recent Posts', 'newtheme' ); ?></h1>
  3.  
  4. <?php
  5.  
  6. // Display our recent posts, showing full content for the very latest, ignoring Aside posts.
  7. $recent_args = array(
  8. 'order' => 'DESC',
  9. 'post__not_in' => get_option( 'sticky_posts' ),
  10. 'tax_query' => array(
  11. 'taxonomy' => 'post_format',
  12. 'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-quote', 'post-format-status' ),
  13. 'field' => 'slug',
  14. 'operator' => 'NOT IN',
  15. ),
  16. ),
  17. 'no_found_rows' => true,
  18. );
  19.  
  20. // Our new query for the Recent Posts section.
  21. $recent = new WP_Query( $recent_args );
  22.  
  23. // The first Recent post is displayed normally
  24. if ( $recent->have_posts() ) : $recent->the_post();
  25.  
  26. // Set $more to 0 in order to only get the first part of the post.
  27. global $more;
  28. $more = 0;
  29.  
  30. get_template_part( 'content', get_post_format() );
  31.  
  32. echo '<ol class="other-recent-posts">';
  33.  
  34. endif;
  35.  
  36. // For all other recent posts, just display the title and comment status.
  37. while ( $recent->have_posts() ) : $recent->the_post(); ?>
  38.  
  39. <li class="entry-title">
  40. <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>
  41. <span class="comments-link">
  42. <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'newtheme' ) . '</span>', __( '<b>1</b> Reply', 'newtheme' ), __( '<b>%</b> Replies', 'newtheme' ) ); ?>
  43. </span>
  44. </li>
  45.  
  46. <?php
  47. endwhile;
  48.  
  49. // If we had some posts, close the <ol>
  50. if ( $recent->post_count > 0 )
  51. echo '</ol>';
  52. ?>
  53. </section><!-- .recent-posts -->

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

  1. <div class="widget-area" role="complementary">
  2. <?php if ( ! dynamic_sidebar( 'sidebar-2' ) ) : ?>
  3.  
  4. <?php
  5. the_widget( 'New_Theme_Ephemera_Widget', '', array( 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>' ) );
  6. ?>
  7.  
  8. <?php endif; // end sidebar widget area ?>
  9. </div><!-- .widget-area -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying page content in the showcase.php page template
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8. ?>
  9.  
  10. <article id="post-<?php the_ID(); ?>" <?php post_class( 'intro' ); ?>>
  11. <header class="entry-header">
  12. <h2 class="entry-title"><?php the_title(); ?></h2>
  13. </header><!-- .entry-header -->
  14.  
  15. <div class="entry-content">
  16. <?php the_content(); ?>
  17. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  18. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  19. </div><!-- .entry-content -->
  20. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying posts in the Image Post Format on index and archive pages
  4.  *
  5.  * Learn more: http://codex.wordpress.org/Post_Formats
  6.  *
  7.  * @package WordPress
  8.  * @subpackage New_Theme
  9.  */
  10. ?>
  11. <article id="post-<?php the_ID(); ?>" <?php post_class( 'indexed' ); ?>>
  12. <header class="entry-header">
  13. <hgroup>
  14. <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>
  15. <h3 class="entry-format"><?php _e( 'Image', 'newtheme' ); ?></h3>
  16. </hgroup>
  17.  
  18. <?php if ( comments_open() && ! post_password_required() ) : ?>
  19. <div class="comments-link">
  20. <?php comments_popup_link( '<span class="leave-reply">' . __( "Reply", 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
  21. </div>
  22. <?php endif; ?>
  23. </header><!-- .entry-header -->
  24.  
  25. <div class="entry-content">
  26. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  27. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  28. </div><!-- .entry-content -->
  29.  
  30. <footer class="entry-meta">
  31. <div class="entry-meta">
  32. <?php
  33. 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' ),
  34. esc_url( get_permalink() ),
  35. get_the_date( 'c' ),
  36. get_the_date(),
  37. esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
  38. esc_attr( sprintf( __( 'View all posts by %s', 'newtheme' ), get_the_author() ) ),
  39. get_the_author()
  40. );
  41. ?>
  42. </div><!-- .entry-meta -->
  43. <div class="entry-meta">
  44. <?php
  45. /* translators: used between list items, there is a space after the comma */
  46. $categories_list = get_the_category_list( __( ', ', 'newtheme' ) );
  47. if ( $categories_list ):
  48. ?>
  49. <span class="cat-links">
  50. <?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list ); ?>
  51. </span>
  52. <?php endif; // End if categories ?>
  53. <?php
  54. /* translators: used between list items, there is a space after the comma */
  55. $tags_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
  56. if ( $tags_list ): ?>
  57. <span class="tag-links">
  58. <?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?>
  59. </span>
  60. <?php endif; // End if $tags_list ?>
  61.  
  62. <?php if ( comments_open() ) : ?>
  63. <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>
  64. <?php endif; // End if comments_open() ?>
  65. </div><!-- .entry-meta -->
  66.  
  67. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  68. </footer><!-- #entry-meta -->
  69. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying posts in the Link Post Format on index and archive pages
  4.  *
  5.  * Learn more: http://codex.wordpress.org/Post_Formats
  6.  *
  7.  * @package WordPress
  8.  * @subpackage New_Theme
  9.  */
  10. ?>
  11.  
  12. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  13. <header class="entry-header">
  14. <hgroup>
  15. <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>
  16. <h3 class="entry-format"><?php _e( 'Link', 'newtheme' ); ?></h3>
  17. </hgroup>
  18.  
  19. <?php if ( comments_open() && ! post_password_required() ) : ?>
  20. <div class="comments-link">
  21. <?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
  22. </div>
  23. <?php endif; ?>
  24. </header><!-- .entry-header -->
  25.  
  26. <?php if ( is_search() ) : // Only display Excerpts for Search ?>
  27. <div class="entry-summary">
  28. <?php the_excerpt(); ?>
  29. </div><!-- .entry-summary -->
  30. <?php else : ?>
  31. <div class="entry-content">
  32. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  33. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  34. </div><!-- .entry-content -->
  35. <?php endif; ?>
  36.  
  37. <footer class="entry-meta">
  38. <?php newtheme_posted_on(); ?>
  39. <?php if ( comments_open() ) : ?>
  40. <span class="sep"> | </span>
  41. <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>
  42. <?php endif; ?>
  43. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  44. </footer><!-- #entry-meta -->
  45. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2.  
  3. <?php
  4. /**
  5.  * The default template for displaying content
  6.  *
  7.  * @package WordPress
  8.  * @subpackage New_Theme
  9.  */
  10. ?>
  11.  
  12. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  13. <header class="entry-header">
  14. <hgroup>
  15. <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>
  16. <h3 class="entry-format"><?php _e( 'Quote', 'newtheme' ); ?></h3>
  17. </hgroup>
  18.  
  19. <div class="entry-meta">
  20. <?php newtheme_posted_on(); ?>
  21. </div><!-- .entry-meta -->
  22.  
  23. <?php if ( comments_open() && ! post_password_required() ) : ?>
  24. <div class="comments-link">
  25. <?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
  26. </div>
  27. <?php endif; ?>
  28. </header><!-- .entry-header -->
  29.  
  30. <?php if ( is_search() ) : // Only display Excerpts for Search ?>
  31. <div class="entry-summary">
  32. <?php the_excerpt(); ?>
  33. </div><!-- .entry-summary -->
  34. <?php else : ?>
  35. <div class="entry-content">
  36. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  37. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  38. </div><!-- .entry-content -->
  39. <?php endif; ?>
  40.  
  41. <footer class="entry-meta">
  42. <?php $show_sep = false; ?>
  43. <?php
  44. /* translators: used between list items, there is a space after the comma */
  45. $categories_list = get_the_category_list( __( ', ', 'newtheme' ) );
  46. if ( $categories_list ):
  47. ?>
  48. <span class="cat-links">
  49. <?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
  50. $show_sep = true; ?>
  51. </span>
  52. <?php endif; // End if categories ?>
  53. <?php
  54. /* translators: used between list items, there is a space after the comma */
  55. $tags_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
  56. if ( $tags_list ):
  57. if ( $show_sep ) : ?>
  58. <span class="sep"> | </span>
  59. <?php endif; // End if $show_sep ?>
  60. <span class="tag-links">
  61. <?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
  62. $show_sep = true; ?>
  63. </span>
  64. <?php endif; // End if $tags_list ?>
  65.  
  66. <?php if ( comments_open() ) : ?>
  67. <?php if ( $show_sep ) : ?>
  68. <span class="sep"> | </span>
  69. <?php endif; // End if $show_sep ?>
  70. <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>
  71. <?php endif; // End if comments_open() ?>
  72.  
  73. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  74. </footer><!-- #entry-meta -->
  75. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying posts in the Status Post Format on index and archive pages
  4.  *
  5.  * Learn more: http://codex.wordpress.org/Post_Formats
  6.  *
  7.  * @package WordPress
  8.  * @subpackage New_Theme
  9.  */
  10. ?>
  11.  
  12. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  13. <header class="entry-header">
  14. <hgroup>
  15. <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>
  16. <h3 class="entry-format"><?php _e( 'Status', 'newtheme' ); ?></h3>
  17. </hgroup>
  18.  
  19. <?php if ( comments_open() && ! post_password_required() ) : ?>
  20. <div class="comments-link">
  21. <?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
  22. </div>
  23. <?php endif; ?>
  24. </header><!-- .entry-header -->
  25.  
  26. <?php if ( is_search() ) : // Only display Excerpts for Search ?>
  27. <div class="entry-summary">
  28. <?php the_excerpt(); ?>
  29. </div><!-- .entry-summary -->
  30. <?php else : ?>
  31. <div class="entry-content">
  32. <div class="avatar"><?php echo get_avatar( get_the_author_meta( 'ID' ), apply_filters( 'newtheme_status_avatar', '65' ) ); ?></div>
  33.  
  34. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  35. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  36. </div><!-- .entry-content -->
  37. <?php endif; ?>
  38.  
  39. <footer class="entry-meta">
  40. <?php newtheme_posted_on(); ?>
  41. <?php if ( comments_open() ) : ?>
  42. <span class="sep"> | </span>
  43. <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>
  44. <?php endif; ?>
  45. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  46. </footer><!-- #entry-meta -->
  47. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying posts in the Aside Post Format on index and archive pages
  4.  *
  5.  * Learn more: http://codex.wordpress.org/Post_Formats
  6.  *
  7.  * @package WordPress
  8.  * @subpackage New_Theme
  9.  */
  10. ?>
  11.  
  12. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  13. <header class="entry-header">
  14. <hgroup>
  15. <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>
  16. <h3 class="entry-format"><?php _e( 'Aside', 'newtheme' ); ?></h3>
  17. </hgroup>
  18.  
  19. <?php if ( comments_open() && ! post_password_required() ) : ?>
  20. <div class="comments-link">
  21. <?php comments_popup_link( '<span class="leave-reply">' . __( 'Reply', 'newtheme' ) . '</span>', _x( '1', 'comments number', 'newtheme' ), _x( '%', 'comments number', 'newtheme' ) ); ?>
  22. </div>
  23. <?php endif; ?>
  24. </header><!-- .entry-header -->
  25.  
  26. <?php if ( is_search() ) : // Only display Excerpts for Search ?>
  27. <div class="entry-summary">
  28. <?php the_excerpt(); ?>
  29. </div><!-- .entry-summary -->
  30. <?php else : ?>
  31. <div class="entry-content">
  32. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  33. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  34. </div><!-- .entry-content -->
  35. <?php endif; ?>
  36.  
  37. <footer class="entry-meta">
  38. <?php newtheme_posted_on(); ?>
  39. <?php if ( comments_open() ) : ?>
  40. <span class="sep"> | </span>
  41. <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>
  42. <?php endif; ?>
  43. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  44. </footer><!-- #entry-meta -->
  45. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying content featured in the showcase.php page template
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8.  
  9. global $feature_class;
  10. ?>
  11. <article id="post-<?php the_ID(); ?>" <?php post_class( $feature_class ); ?>>
  12. <header class="entry-header">
  13. <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>
  14.  
  15. <div class="entry-meta">
  16. <?php newtheme_posted_on(); ?>
  17. </div><!-- .entry-meta -->
  18. </header><!-- .entry-header -->
  19.  
  20. <div class="entry-summary">
  21. <?php the_excerpt(); ?>
  22. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  23. </div><!-- .entry-content -->
  24.  
  25. <footer class="entry-meta">
  26. <?php
  27. /* translators: used between list items, there is a space after the comma */
  28. $tag_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
  29. if ( '' != $tag_list ) {
  30. $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' );
  31. } else {
  32. $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' );
  33. }
  34. $utility_text,
  35. /* translators: used between list items, there is a space after the comma */
  36. get_the_category_list( __( ', ', 'newtheme' ) ),
  37. $tag_list,
  38. esc_url( get_permalink() ),
  39. the_title_attribute( 'echo=0' )
  40. );
  41. ?>
  42.  
  43. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  44. </footer><!-- .entry-meta -->
  45. </article><!-- #post-<?php the_ID(); ?> -->

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:

  1. <?php
  2. /**
  3.  * The template for displaying posts in the Gallery Post Format on index and archive pages
  4.  *
  5.  * Learn more: http://codex.wordpress.org/Post_Formats
  6.  *
  7.  * @package WordPress
  8.  * @subpackage New_Theme
  9.  */
  10. ?>
  11.  
  12. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  13. <header class="entry-header">
  14. <hgroup>
  15. <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>
  16. <h3 class="entry-format"><?php _e( 'Gallery', 'newtheme' ); ?></h3>
  17. </hgroup>
  18.  
  19. <div class="entry-meta">
  20. <?php newtheme_posted_on(); ?>
  21. </div><!-- .entry-meta -->
  22. </header><!-- .entry-header -->
  23.  
  24. <?php if ( is_search() ) : // Only display Excerpts for search pages ?>
  25. <div class="entry-summary">
  26. <?php the_excerpt(); ?>
  27. </div><!-- .entry-summary -->
  28. <?php else : ?>
  29. <div class="entry-content">
  30. <?php if ( post_password_required() ) : ?>
  31. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  32.  
  33. <?php else : ?>
  34. <?php
  35. $images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
  36. if ( $images ) :
  37. $total_images = count( $images );
  38. $image = array_shift( $images );
  39. $image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' );
  40. ?>
  41.  
  42. <figure class="gallery-thumb">
  43. <a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
  44. </figure><!-- .gallery-thumb -->
  45.  
  46. <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' ),
  47. 'href="' . esc_url( get_permalink() ) . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
  48. number_format_i18n( $total_images )
  49. ); ?></em></p>
  50. <?php endif; ?>
  51. <?php the_excerpt(); ?>
  52. <?php endif; ?>
  53. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  54. </div><!-- .entry-content -->
  55. <?php endif; ?>
  56.  
  57. <footer class="entry-meta">
  58. <?php $show_sep = false; ?>
  59. <?php
  60. /* translators: used between list items, there is a space after the comma */
  61. $categories_list = get_the_category_list( __( ', ', 'newtheme' ) );
  62. if ( $categories_list ):
  63. ?>
  64. <span class="cat-links">
  65. <?php printf( __( '<span class="%1$s">Posted in</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-cat-links', $categories_list );
  66. $show_sep = true; ?>
  67. </span>
  68. <?php endif; // End if categories ?>
  69. <?php
  70. /* translators: used between list items, there is a space after the comma */
  71. $tags_list = get_the_tag_list( '', __( ', ', 'newtheme' ) );
  72. if ( $tags_list ):
  73. if ( $show_sep ) : ?>
  74. <span class="sep"> | </span>
  75. <?php endif; // End if $show_sep ?>
  76. <span class="tag-links">
  77. <?php printf( __( '<span class="%1$s">Tagged</span> %2$s', 'newtheme' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list );
  78. $show_sep = true; ?>
  79. </span>
  80. <?php endif; // End if $tags_list ?>
  81.  
  82. <?php if ( comments_open() ) : ?>
  83. <?php if ( $show_sep ) : ?>
  84. <span class="sep"> | </span>
  85. <?php endif; // End if $show_sep ?>
  86. <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>
  87. <?php endif; // End if comments_open() ?>
  88.  
  89. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  90. </footer><!-- #entry-meta -->
  91. </article><!-- #post-<?php the_ID(); ?> -->

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

  1. <?php if ( post_password_required() ) : ?>
  2. <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?>
  3.  
  4. <?php else : ?>
  5. <?php
  6. $images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 999 ) );
  7. if ( $images ) :
  8. $total_images = count( $images );
  9. $image = array_shift( $images );
  10. $image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' );
  11. ?>
  12.  
  13. <figure class="gallery-thumb">
  14. <a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
  15. </figure><!-- .gallery-thumb -->
  16.  
  17. <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' ),
  18. 'href="' . esc_url( get_permalink() ) . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'newtheme' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
  19. number_format_i18n( $total_images )
  20. ); ?></em></p>
  21. <?php endif; ?>

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

WordPress 3.x para desarrolladores: Temas y plantillas, page.php, sidebar-page.php y content-page.php

1

Seguimos con más plantillas para nuestro tema. Las dos siguientes son bastante sencillas.

 

PAGE.PHP

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

  1. <?php
  2. /**
  3.  * The template for displaying all pages.
  4.  *
  5.  * This is the template that displays all pages by default.
  6.  * Please note that this is the WordPress construct of pages
  7.  * and that other 'pages' on your WordPress site will use a
  8.  * different template.
  9.  *
  10.  * @package WordPress
  11.  * @subpackage New_Theme
  12.  */
  13.  
  14. get_header(); ?>
  15.  
  16. <div id="primary">
  17. <div id="content" role="main">
  18.  
  19. <?php while ( have_posts() ) : the_post(); ?>
  20.  
  21. <?php get_template_part( 'content', 'page' ); ?>
  22.  
  23. <?php comments_template( '', true ); ?>
  24.  
  25. <?php endwhile; // end of the loop. ?>
  26.  
  27. </div><!-- #content -->
  28. </div><!-- #primary -->
  29.  
  30. <?php get_footer(); ?>

Poco puedo comentar del código que no hayamos visto ya. Se llama a la cabecera; se crean las capas para contener el contenido de la página; se crea el bucle que comprobará si hay posts; se recupera la plantilla content-page.php que dará formato al contenido; se recupera la plantilla de comentarios siempre que el administrador los haya habilitado para este contenido, y se recupera la plantilla del pie de página.

 

SIDEBAR-PAGE.PHP

Creamos el archivo sidebar-page.php y añadimos el siguiente código:

  1. <?php
  2. /**
  3.  * Template Name: Sidebar Template
  4.  * Description: A Page Template that adds a sidebar to pages
  5.  *
  6.  * @package WordPress
  7.  * @subpackage New_Theme
  8.  */
  9.  
  10. get_header(); ?>
  11.  
  12. <div id="primary">
  13. <div id="content" role="main">
  14.  
  15. <?php while ( have_posts() ) : the_post(); ?>
  16.  
  17. <?php get_template_part( 'content', 'page' ); ?>
  18.  
  19. <?php comments_template( '', true ); ?>
  20.  
  21. <?php endwhile; // end of the loop. ?>
  22.  
  23. </div><!-- #content -->
  24. </div><!-- #primary -->
  25.  
  26. <?php get_sidebar(); ?>
  27. <?php get_footer(); ?>

Prácticamente es el mismo código, con la única diferencia de que antes de llamar a la plantilla del pie de página llamamos a la plantilla del sidebar.

 

CONTENT-PAGE.PHP

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

  1. <?php
  2. /**
  3.  * The template used for displaying page content in page.php
  4.  *
  5.  * @package WordPress
  6.  * @subpackage New_Theme
  7.  */
  8. ?>
  9.  
  10. <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
  11. <header class="entry-header">
  12. <h1 class="entry-title"><?php the_title(); ?></h1>
  13. </header><!-- .entry-header -->
  14.  
  15. <div class="entry-content">
  16. <?php the_content(); ?>
  17. <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'newtheme' ) . '</span>', 'after' => '</div>' ) ); ?>
  18. </div><!-- .entry-content -->
  19. <footer class="entry-meta">
  20. <?php edit_post_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  21. </footer><!-- .entry-meta -->
  22. </article><!-- #post-<?php the_ID(); ?> -->

Este código también es bastante sencillo.

Creamos una etiqueta article, la cual tendrá como id el texto post- seguido del id del post, recuperado con la función the_ID(). Además a esta etiqueta le añadimos las clases de estilos correspondiente a los post, utilizando para ello la función post_class().

A continuación se crea la cabecera del post y se añade el título con la función the_title().

Ya en el contenido se hace una llamada a la función the_content() que recuperará el contenido del post, y seguidamente se hace una llamada a wp_link_pages() que creará un paginador para el post en caso de que sea necesario.

Por último se crea el pie del post con el link para poder editarlo.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, widgets.php

0

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:

  1. <?php
  2.  
  3. /**
  4.  * Makes a custom Widget for displaying Aside, Link, Status, and Quote Posts available with New Theme
  5.  *
  6.  * Learn more: http://codex.wordpress.org/Widgets_API#Developing_Widgets
  7.  *
  8.  * @package WordPress
  9.  * @subpackage Nwe_Theme
  10.  */
  11. class New_Theme_Ephemera_Widget extends WP_Widget {
  12.  
  13. }

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

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

  1. <?php
  2.  
  3. /**
  4. * Constructor
  5. *
  6. * @return void
  7. **/
  8. function New_Theme_Ephemera_Widget() {
  9. $widget_ops = array( 'classname' => 'widget_newtheme_ephemera', 'description' => __( 'Use this widget to list your recent Aside, Status, Quote, and Link posts', 'newtheme' ) );
  10. $this->WP_Widget( 'widget_newtheme_ephemera', __( 'New Theme Ephemera', 'newtheme' ), $widget_ops );
  11. $this->alt_option_name = 'widget_newtheme_ephemera';
  12.  
  13. add_action( 'save_post', array(&$this, 'flush_widget_cache' ) );
  14. add_action( 'deleted_post', array(&$this, 'flush_widget_cache' ) );
  15. add_action( 'switch_theme', array(&$this, 'flush_widget_cache' ) );
  16. }

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.

  1. <?php
  2.  
  3. /**
  4. * Outputs the HTML for this widget.
  5. *
  6. * @param array An array of standard parameters for widgets in this theme
  7. * @param array An array of settings for this widget instance
  8. * @return void Echoes it's output
  9. **/
  10. function widget( $args, $instance ) {
  11. $cache = wp_cache_get( 'widget_newtheme_ephemera', 'widget' );
  12.  
  13. if ( !is_array( $cache ) )
  14. $cache = array();
  15.  
  16. if ( ! isset( $args['widget_id'] ) )
  17. $args['widget_id'] = null;
  18.  
  19. if ( isset( $cache[$args['widget_id']] ) ) {
  20. echo $cache[$args['widget_id']];
  21. return;
  22. }
  23.  
  24. extract( $args, EXTR_SKIP );
  25.  
  26. $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Ephemera', 'newtheme' ) : $instance['title'], $instance, $this->id_base);
  27.  
  28. if ( ! isset( $instance['number'] ) )
  29. $instance['number'] = '10';
  30.  
  31. if ( ! $number = absint( $instance['number'] ) )
  32. $number = 10;
  33.  
  34. $ephemera_args = array(
  35. 'order' => 'DESC',
  36. 'posts_per_page' => $number,
  37. 'no_found_rows' => true,
  38. 'post_status' => 'publish',
  39. 'post__not_in' => get_option( 'sticky_posts' ),
  40. 'tax_query' => array(
  41. 'taxonomy' => 'post_format',
  42. 'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-status', 'post-format-quote' ),
  43. 'field' => 'slug',
  44. 'operator' => 'IN',
  45. ),
  46. ),
  47. );
  48. $ephemera = new WP_Query( $ephemera_args );
  49.  
  50. if ( $ephemera->have_posts() ) :
  51. echo $before_widget;
  52. echo $before_title;
  53. echo $title; // Can set this with a widget option, or omit altogether
  54. echo $after_title;
  55. ?>
  56. <ol>
  57. <?php while ( $ephemera->have_posts() ) : $ephemera->the_post(); ?>
  58.  
  59. <?php if ( 'link' != get_post_format() ) : ?>
  60.  
  61. <li class="widget-entry-title">
  62. <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>
  63. <span class="comments-link">
  64. <?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' ) ); ?>
  65. </span>
  66. </li>
  67.  
  68. <?php else : ?>
  69.  
  70. <li class="widget-entry-title">
  71. <?php
  72. // Grab first link from the post content. If none found, use the post permalink as fallback.
  73. $link_url = newtheme_url_grabber();
  74.  
  75. if ( empty( $link_url ) )
  76. $link_url = get_permalink();
  77. ?>
  78. <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>
  79. <span class="comments-link">
  80. <?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' ) ); ?>
  81. </span>
  82. </li>
  83.  
  84. <?php endif; ?>
  85.  
  86. <?php endwhile; ?>
  87. </ol>
  88. <?php
  89.  
  90. echo $after_widget;
  91.  
  92. // Reset the post globals as this query will have stomped on it
  93. wp_reset_postdata();
  94.  
  95. // end check for ephemeral posts
  96. endif;
  97.  
  98. $cache[$args['widget_id']] = ob_get_flush();
  99. wp_cache_set( 'widget_newtheme_ephemera', $cache, 'widget' );
  100. }

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

  1. <?php
  2.  
  3. $cache = wp_cache_get( 'widget_newtheme_ephemera', 'widget' );
  4.  
  5. if ( !is_array( $cache ) )
  6. $cache = array();
  7.  
  8. if ( ! isset( $args['widget_id'] ) )
  9. $args['widget_id'] = null;
  10.  
  11. if ( isset( $cache[$args['widget_id']] ) ) {
  12. echo $cache[$args['widget_id']];
  13. return;
  14. }

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.

  1. <?php
  2.  
  3. extract( $args, EXTR_SKIP );
  4.  
  5. $title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Ephemera', 'newtheme' ) : $instance['title'], $instance, $this->id_base);
  6.  
  7. if ( ! isset( $instance['number'] ) )
  8. $instance['number'] = '10';
  9.  
  10. if ( ! $number = absint( $instance['number'] ) )
  11. $number = 10;
  12.  
  13. $ephemera_args = array(
  14. 'order' => 'DESC',
  15. 'posts_per_page' => $number,
  16. 'no_found_rows' => true,
  17. 'post_status' => 'publish',
  18. 'post__not_in' => get_option( 'sticky_posts' ),
  19. 'tax_query' => array(
  20. 'taxonomy' => 'post_format',
  21. 'terms' => array( 'post-format-aside', 'post-format-link', 'post-format-status', 'post-format-quote' ),
  22. 'field' => 'slug',
  23. 'operator' => 'IN',
  24. ),
  25. ),
  26. );
  27. $ephemera = new WP_Query( $ephemera_args );

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.

  1. <?php
  2.  
  3. if ( $ephemera->have_posts() ) :
  4. echo $before_widget;
  5. echo $before_title;
  6. echo $title; // Can set this with a widget option, or omit altogether
  7. echo $after_title;
  8. ?>
  9. <ol>
  10. <?php while ( $ephemera->have_posts() ) : $ephemera->the_post(); ?>
  11.  
  12. <?php if ( 'link' != get_post_format() ) : ?>
  13.  
  14. <li class="widget-entry-title">
  15. <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>
  16. <span class="comments-link">
  17. <?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' ) ); ?>
  18. </span>
  19. </li>
  20.  
  21. <?php else : ?>
  22.  
  23. <li class="widget-entry-title">
  24. <?php
  25. // Grab first link from the post content. If none found, use the post permalink as fallback.
  26. $link_url = newtheme_url_grabber();
  27.  
  28. if ( empty( $link_url ) )
  29. $link_url = get_permalink();
  30. ?>
  31. <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>
  32. <span class="comments-link">
  33. <?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' ) ); ?>
  34. </span>
  35. </li>
  36.  
  37. <?php endif; ?>
  38.  
  39. <?php endwhile; ?>
  40. </ol>
  41. <?php
  42.  
  43. echo $after_widget;
  44.  
  45. // Reset the post globals as this query will have stomped on it
  46. wp_reset_postdata();
  47.  
  48. // end check for ephemeral posts
  49. endif;

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.

  1. <?php
  2.  
  3. $cache[$args['widget_id']] = ob_get_flush();
  4. wp_cache_set( 'widget_newtheme_ephemera', $cache, 'widget' );

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

  1. <?php
  2.  
  3. /**
  4. * Deals with the settings when they are saved by the admin. Here is
  5. * where any validation should be dealt with.
  6. **/
  7. function update( $new_instance, $old_instance ) {
  8. $instance = $old_instance;
  9. $instance['title'] = strip_tags( $new_instance['title'] );
  10. $instance['number'] = (int) $new_instance['number'];
  11. $this->flush_widget_cache();
  12.  
  13. $alloptions = wp_cache_get( 'alloptions', 'options' );
  14. if ( isset( $alloptions['widget_newtheme_ephemera'] ) )
  15. delete_option( 'widget_newtheme_ephemera' );
  16.  
  17. return $instance;
  18. }

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

  1. <?php
  2.  
  3. function flush_widget_cache() {
  4. wp_cache_delete( 'widget_newtheme_ephemera', 'widget' );
  5. }

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

  1. <?php
  2.  
  3. /**
  4. * Displays the form for this widget on the Widgets page of the WP Admin area.
  5. **/
  6. function form( $instance ) {
  7. $title = isset( $instance['title']) ? esc_attr( $instance['title'] ) : '';
  8. $number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 10;
  9. ?>
  10. <p><label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Title:', 'newtheme' ); ?></label>
  11. <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>
  12.  
  13. <p><label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>"><?php _e( 'Number of posts to show:', 'newtheme' ); ?></label>
  14. <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>
  15. <?php
  16. }

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

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, theme-options.php

0

Nuestro tema va tomando poco a poco forma. Hoy vamos a crear el archivo theme-options.php que contendrá toda la lógica de las opciones de administración.

 

THEME-OPTIONS.PHP

Creamos el archivo theme-options.php y añadimos el siguiente código:

  1. <?php
  2.  
  3. /**
  4.  * Properly enqueue styles and scripts for our theme options page.
  5.  *
  6.  * This function is attached to the admin_enqueue_scripts action hook.
  7.  */
  8. function newtheme_admin_enqueue_scripts( $hook_suffix ) {
  9. wp_enqueue_style( 'newtheme-theme-options', get_template_directory_uri() . '/inc/theme-options.css', false, '2011-04-28' );
  10. wp_enqueue_script( 'newtheme-theme-options', get_template_directory_uri() . '/inc/theme-options.js', array( 'farbtastic' ), '2011-06-10' );
  11. wp_enqueue_style( 'farbtastic' );
  12. }
  13. add_action( 'admin_print_styles-appearance_page_theme_options', 'newtheme_admin_enqueue_scripts' );

Esta función añade un archivo css y un archivo javascript a la cabecera al apartado apariencia de la administración de WordPress.

  1. <?php
  2.  
  3. /**
  4.  * Register the form setting for our newtheme_options array.
  5.  *
  6.  * This function is attached to the admin_init action hook.
  7.  *
  8.  * This call to register_setting() registers a validation callback, newtheme_theme_options_validate(),
  9.  * which is used when the option is saved, to ensure that our option values are complete, properly
  10.  * formatted, and safe.
  11.  */
  12. function newtheme_theme_options_init() {
  13.  
  14. register_setting(
  15. 'newtheme_options', // Options group, see settings_fields() call in newtheme_theme_options_render_page()
  16. 'newtheme_theme_options', // Database option, see newtheme_get_theme_options()
  17. 'newtheme_theme_options_validate' // The sanitization callback, see newtheme_theme_options_validate()
  18. );
  19.  
  20. // Register our settings field group
  21. add_settings_section(
  22. 'general', // Unique identifier for the settings section
  23. '', // Section title (we don't want one)
  24. '__return_false', // Section callback (we don't want anything)
  25. 'theme_options' // Menu slug, used to uniquely identify the page; see newtheme_theme_options_add_page()
  26. );
  27.  
  28. // Register our individual settings fields
  29. add_settings_field(
  30. 'color_scheme', // Unique identifier for the field for this section
  31. __( 'Color Scheme', 'newtheme' ), // Setting field label
  32. 'newtheme_settings_field_color_scheme', // Function that renders the settings field
  33. 'theme_options', // Menu slug, used to uniquely identify the page; see newtheme_theme_options_add_page()
  34. 'general' // Settings section. Same as the first argument in the add_settings_section() above
  35. );
  36.  
  37. add_settings_field( 'link_color', __( 'Link Color', 'newtheme' ), 'newtheme_settings_field_link_color', 'theme_options', 'general' );
  38. add_settings_field( 'layout', __( 'Default Layout', 'newtheme' ), 'newtheme_settings_field_layout', 'theme_options', 'general' );
  39. }
  40. add_action( 'admin_init', 'newtheme_theme_options_init' );

Esta función registra la configuración por defecto del tema y añade varios apartados para la administración.

  1. <?php
  2.  
  3. /**
  4.  * Change the capability required to save the 'newtheme_options' options group.
  5.  *
  6.  * @see newtheme_theme_options_init() First parameter to register_setting() is the name of the options group.
  7.  * @see newtheme_theme_options_add_page() The edit_theme_options capability is used for viewing the page.
  8.  *
  9.  * By default, the options groups for all registered settings require the manage_options capability.
  10.  * This filter is required to change our theme options page to edit_theme_options instead.
  11.  * By default, only administrators have either of these capabilities, but the desire here is
  12.  * to allow for finer-grained control for roles and users.
  13.  *
  14.  * @param string $capability The capability used for the page, which is manage_options by default.
  15.  * @return string The capability to actually use.
  16.  */
  17. function newtheme_option_page_capability( $capability ) {
  18. return 'edit_theme_options';
  19. }
  20. add_filter( 'option_page_capability_newtheme_options', 'newtheme_option_page_capability' );

Esta función permite cambiar las opciones del tema. Es obligatorio para controlar los diversos usuarios y roles que tengan acceso.

  1. <?php
  2.  
  3. /**
  4.  * Add our theme options page to the admin menu, including some help documentation.
  5.  *
  6.  * This function is attached to the admin_menu action hook.
  7.  */
  8. function newtheme_theme_options_add_page() {
  9. $theme_page = add_theme_page(
  10. __( 'Theme Options', 'newtheme' ), // Name of page
  11. __( 'Theme Options', 'newtheme' ), // Label in menu
  12. 'edit_theme_options', // Capability required
  13. 'theme_options', // Menu slug, used to uniquely identify the page
  14. 'newtheme_theme_options_render_page' // Function that renders the options page
  15. );
  16.  
  17. if ( ! $theme_page )
  18. return;
  19.  
  20. add_action( "load-$theme_page", 'newtheme_theme_options_help' );
  21. }
  22. add_action( 'admin_menu', 'newtheme_theme_options_add_page' );

Añade la página de opciones de nuestro tema al menú de administración, incluyendo algo de documentación a la ayuda.

  1. <?php
  2.  
  3. function newtheme_theme_options_help() {
  4.  
  5. $help = '<p>' . __( 'Some themes provide customization options that are grouped together on a Theme Options screen. If you change themes, options may change or disappear, as they are theme-specific. Your current theme, Twenty Eleven, provides the following Theme Options:', 'newtheme' ) . '</p>' .
  6. '<ol>' .
  7. '<li>' . __( '<strong>Color Scheme</strong>: You can choose a color palette of "Light" (light background with dark text) or "Dark" (dark background with light text) for your site.', 'newtheme' ) . '</li>' .
  8. '<li>' . __( '<strong>Link Color</strong>: You can choose the color used for text links on your site. You can enter the HTML color or hex code, or you can choose visually by clicking the "Select a Color" button to pick from a color wheel.', 'newtheme' ) . '</li>' .
  9. '<li>' . __( '<strong>Default Layout</strong>: You can choose if you want your site&#8217;s default layout to have a sidebar on the left, the right, or not at all.', 'newtheme' ) . '</li>' .
  10. '</ol>' .
  11. '<p>' . __( 'Remember to click "Save Changes" to save any changes you have made to the theme options.', 'newtheme' ) . '</p>';
  12.  
  13. $sidebar = '<p><strong>' . __( 'For more information:', 'newtheme' ) . '</strong></p>' .
  14. '<p>' . __( '<a href="http://codex.wordpress.org/Appearance_Theme_Options_Screen" target="_blank">Documentation on Theme Options</a>', 'newtheme' ) . '</p>' .
  15. '<p>' . __( '<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>', 'newtheme' ) . '</p>';
  16.  
  17. $screen = get_current_screen();
  18.  
  19. if ( method_exists( $screen, 'add_help_tab' ) ) {
  20. // WordPress 3.3
  21. $screen->add_help_tab( array(
  22. 'title' => __( 'Overview', 'newtheme' ),
  23. 'id' => 'theme-options-help',
  24. 'content' => $help,
  25. )
  26. );
  27.  
  28. $screen->set_help_sidebar( $sidebar );
  29. } else {
  30. // WordPress 3.2
  31. add_contextual_help( $screen, $help . $sidebar );
  32. }
  33. }

Esta es la función que añade la ayuda que comentaba en la función anterior. Aquí además podemos ver como se añade un condicional para añadir retrocompatibilidad con versiones anteriores a la 3.3 y la 3.2.

  1. <?php
  2.  
  3. /**
  4.  * Returns an array of color schemes registered for New Theme.
  5.  */
  6. function newtheme_color_schemes() {
  7. $color_scheme_options = array(
  8. 'light' => array(
  9. 'value' => 'light',
  10. 'label' => __( 'Light', 'newtheme' ),
  11. 'thumbnail' => get_template_directory_uri() . '/inc/images/light.png',
  12. 'default_link_color' => '#1b8be0',
  13. ),
  14. 'dark' => array(
  15. 'value' => 'dark',
  16. 'label' => __( 'Dark', 'newtheme' ),
  17. 'thumbnail' => get_template_directory_uri() . '/inc/images/dark.png',
  18. 'default_link_color' => '#e4741f',
  19. ),
  20. );
  21.  
  22. return apply_filters( 'newtheme_color_schemes', $color_scheme_options );
  23. }

Esta función devuelve un array con los esquemas de color para cada versión del tema.

  1. <?php
  2.  
  3. /**
  4.  * Returns an array of layout options registered for New Theme.
  5.  */
  6. function newtheme_layouts() {
  7. $layout_options = array(
  8. 'content-sidebar' => array(
  9. 'value' => 'content-sidebar',
  10. 'label' => __( 'Content on left', 'newtheme' ),
  11. 'thumbnail' => get_template_directory_uri() . '/inc/images/content-sidebar.png',
  12. ),
  13. 'sidebar-content' => array(
  14. 'value' => 'sidebar-content',
  15. 'label' => __( 'Content on right', 'newtheme' ),
  16. 'thumbnail' => get_template_directory_uri() . '/inc/images/sidebar-content.png',
  17. ),
  18. 'content' => array(
  19. 'value' => 'content',
  20. 'label' => __( 'One-column, no sidebar', 'newtheme' ),
  21. 'thumbnail' => get_template_directory_uri() . '/inc/images/content.png',
  22. ),
  23. );
  24.  
  25. return apply_filters( 'newtheme_layouts', $layout_options );
  26. }

Devuelve un array con las opciones para cada tipo de estructura del diseño.

  1. <?php
  2.  
  3. /**
  4.  * Returns the default options for New Theme.
  5.  */
  6. function newtheme_get_default_theme_options() {
  7. $default_theme_options = array(
  8. 'color_scheme' => 'light',
  9. 'link_color' => newtheme_get_default_link_color( 'light' ),
  10. 'theme_layout' => 'content-sidebar',
  11. );
  12.  
  13. if ( is_rtl() )
  14. $default_theme_options['theme_layout'] = 'sidebar-content';
  15.  
  16. return apply_filters( 'newtheme_default_theme_options', $default_theme_options );
  17. }

Devuelve las opciones por defecto del tema.

  1. <?php
  2.  
  3. /**
  4.  * Returns the default link color for New Theme, based on color scheme.
  5.  *
  6.  *
  7.  * @param $string $color_scheme Color scheme. Defaults to the active color scheme.
  8.  * @return $string Color.
  9. */
  10. function newtheme_get_default_link_color( $color_scheme = null ) {
  11. if ( null === $color_scheme ) {
  12. $options = newtheme_get_theme_options();
  13. $color_scheme = $options['color_scheme'];
  14. }
  15.  
  16. $color_schemes = newtheme_color_schemes();
  17. if ( ! isset( $color_schemes[ $color_scheme ] ) )
  18. return false;
  19.  
  20. return $color_schemes[ $color_scheme ]['default_link_color'];
  21. }

Devuelve el color por defecto para los vínculos.

  1. <?php
  2.  
  3. /**
  4.  * Returns the options array for New Theme.
  5.  */
  6. function newtheme_get_theme_options() {
  7. return get_option( 'newtheme_theme_options', newtheme_get_default_theme_options() );
  8. }

Devuelve un array con todas las opciones del tema.

  1. <?php
  2.  
  3. /**
  4.  * Renders the Color Scheme setting field.
  5.  */
  6. function newtheme_settings_field_color_scheme() {
  7. $options = newtheme_get_theme_options();
  8.  
  9. foreach ( newtheme_color_schemes() as $scheme ) {
  10. ?>
  11. <div class="layout image-radio-option color-scheme">
  12. <label class="description">
  13. <input type="radio" name="newtheme_theme_options[color_scheme]" value="<?php echo esc_attr( $scheme['value'] ); ?>" <?php checked( $options['color_scheme'], $scheme['value'] ); ?> />
  14. <input type="hidden" id="default-color-<?php echo esc_attr( $scheme['value'] ); ?>" value="<?php echo esc_attr( $scheme['default_link_color'] ); ?>" />
  15. <span>
  16. <img src="<?php echo esc_url( $scheme['thumbnail'] ); ?>" width="136" height="122" alt="" />
  17. <?php echo $scheme['label']; ?>
  18. </span>
  19. </label>
  20. </div>
  21. <?php
  22. }
  23. }

Esta función genera el grupo de radio buttons que permitirá elegir entre un esquema de color u otro.

  1. <?php
  2.  
  3. /**
  4.  * Renders the Link Color setting field.
  5.  */
  6. function newtheme_settings_field_link_color() {
  7. $options = newtheme_get_theme_options();
  8. ?>
  9. <input type="text" name="newtheme_theme_options[link_color]" id="link-color" value="<?php echo esc_attr( $options['link_color'] ); ?>" />
  10. <a href="#" class="pickcolor hide-if-no-js" id="link-color-example"></a>
  11. <input type="button" class="pickcolor button hide-if-no-js" value="<?php esc_attr_e( 'Select a Color', 'newtheme' ); ?>" />
  12. <div id="colorPickerDiv" style="z-index: 100; background:#eee; border:1px solid #ccc; position:absolute; display:none;"></div>
  13. <br />
  14. <span><?php printf( __( 'Default color: %s', 'newtheme' ), '<span id="default-color">' . newtheme_get_default_link_color( $options['color_scheme'] ) . '</span>' ); ?></span>
  15. <?php
  16. }

Esta función genera el formulario para poder elegir el color de los vínculos.

  1. <?php
  2.  
  3. /**
  4.  * Renders the Layout setting field.
  5.  */
  6. function newtheme_settings_field_layout() {
  7. $options = newtheme_get_theme_options();
  8. foreach ( newtheme_layouts() as $layout ) {
  9. ?>
  10. <div class="layout image-radio-option theme-layout">
  11. <label class="description">
  12. <input type="radio" name="newtheme_theme_options[theme_layout]" value="<?php echo esc_attr( $layout['value'] ); ?>" <?php checked( $options['theme_layout'], $layout['value'] ); ?> />
  13. <span>
  14. <img src="<?php echo esc_url( $layout['thumbnail'] ); ?>" width="136" height="122" alt="" />
  15. <?php echo $layout['label']; ?>
  16. </span>
  17. </label>
  18. </div>
  19. <?php
  20. }
  21. }

Esta función genera el campo para elegir la estructura del blog.

  1. <?php
  2.  
  3. /**
  4.  * Returns the options array for New Theme.
  5.  */
  6. function newtheme_theme_options_render_page() {
  7. ?>
  8. <div class="wrap">
  9. <?php screen_icon(); ?>
  10. <?php $theme_name = function_exists( 'wp_get_theme' ) ? wp_get_theme() : get_current_theme(); ?>
  11. <h2><?php printf( __( '%s Theme Options', 'newtheme' ), $theme_name ); ?></h2>
  12. <?php settings_errors(); ?>
  13.  
  14. <form method="post" action="options.php">
  15. <?php
  16. settings_fields( 'newtheme_options' );
  17. do_settings_sections( 'theme_options' );
  18. submit_button();
  19. ?>
  20. </form>
  21. </div>
  22. <?php
  23. }

Función que genera todo el formulario de opciones.

  1. <?php
  2.  
  3. /**
  4.  * Sanitize and validate form input. Accepts an array, return a sanitized array.
  5.  *
  6.  * @see newtheme_theme_options_init()
  7.  * @todo set up Reset Options action
  8.  */
  9. function newtheme_theme_options_validate( $input ) {
  10. $output = $defaults = newtheme_get_default_theme_options();
  11.  
  12. // Color scheme must be in our array of color scheme options
  13. if ( isset( $input['color_scheme'] ) && array_key_exists( $input['color_scheme'], newtheme_color_schemes() ) )
  14. $output['color_scheme'] = $input['color_scheme'];
  15.  
  16. // Our defaults for the link color may have changed, based on the color scheme.
  17. $output['link_color'] = $defaults['link_color'] = newtheme_get_default_link_color( $output['color_scheme'] );
  18.  
  19. // Link color must be 3 or 6 hexadecimal characters
  20. if ( isset( $input['link_color'] ) && preg_match( '/^#?([a-f0-9]{3}){1,2}$/i', $input['link_color'] ) )
  21. $output['link_color'] = '#' . strtolower( ltrim( $input['link_color'], '#' ) );
  22.  
  23. // Theme layout must be in our array of theme layout options
  24. if ( isset( $input['theme_layout'] ) && array_key_exists( $input['theme_layout'], newtheme_layouts() ) )
  25. $output['theme_layout'] = $input['theme_layout'];
  26.  
  27. return apply_filters( 'newtheme_theme_options_validate', $output, $input, $defaults );
  28. }

Esta función valida que los datos del formulario son correctos.

  1. <?php
  2.  
  3. /**
  4.  * Enqueue the styles for the current color scheme.
  5.  */
  6. function newtheme_enqueue_color_scheme() {
  7. $options = newtheme_get_theme_options();
  8. $color_scheme = $options['color_scheme'];
  9.  
  10. if ( 'dark' == $color_scheme )
  11. wp_enqueue_style( 'dark', get_template_directory_uri() . '/colors/dark.css', array(), null );
  12.  
  13. do_action( 'newtheme_enqueue_color_scheme', $color_scheme );
  14. }
  15. add_action( 'wp_enqueue_scripts', 'newtheme_enqueue_color_scheme' );

Función que cambiará el estilo actual de la página dependiendo del color de esquema elegido.

  1. <?php
  2.  
  3. /**
  4.  * Add a style block to the theme for the current link color.
  5.  *
  6.  * This function is attached to the wp_head action hook.
  7.  */
  8. function newtheme_print_link_color_style() {
  9. $options = newtheme_get_theme_options();
  10. $link_color = $options['link_color'];
  11.  
  12. $default_options = newtheme_get_default_theme_options();
  13.  
  14. // Don't do anything if the current link color is the default.
  15. if ( $default_options['link_color'] == $link_color )
  16. return;
  17. ?>
  18. <style>
  19. /* Link color */
  20. a,
  21. #site-title a:focus,
  22. #site-title a:hover,
  23. #site-title a:active,
  24. .entry-title a:hover,
  25. .entry-title a:focus,
  26. .entry-title a:active,
  27. .widget_newtheme_ephemera .comments-link a:hover,
  28. section.recent-posts .other-recent-posts a[rel="bookmark"]:hover,
  29. section.recent-posts .other-recent-posts .comments-link a:hover,
  30. .format-image footer.entry-meta a:hover,
  31. #site-generator a:hover {
  32. color: <?php echo $link_color; ?>;
  33. }
  34. section.recent-posts .other-recent-posts .comments-link a:hover {
  35. border-color: <?php echo $link_color; ?>;
  36. }
  37. article.feature-image.small .entry-summary p a:hover,
  38. .entry-header .comments-link a:hover,
  39. .entry-header .comments-link a:focus,
  40. .entry-header .comments-link a:active,
  41. .feature-slider a.active {
  42. background-color: <?php echo $link_color; ?>;
  43. }
  44. </style>
  45. <?php
  46. }
  47. add_action( 'wp_head', 'newtheme_print_link_color_style' );

Función que añadirá el color a los vínculos a través de los estilos si este no es el mismo que el de defecto.

  1. <?php
  2.  
  3. /**
  4.  * Adds New Theme layout classes to the array of body classes.
  5.  */
  6. function newtheme_layout_classes( $existing_classes ) {
  7. $options = newtheme_get_theme_options();
  8. $current_layout = $options['theme_layout'];
  9.  
  10. if ( in_array( $current_layout, array( 'content-sidebar', 'sidebar-content' ) ) )
  11. $classes = array( 'two-column' );
  12. else
  13. $classes = array( 'one-column' );
  14.  
  15. if ( 'content-sidebar' == $current_layout )
  16. $classes[] = 'right-sidebar';
  17. elseif ( 'sidebar-content' == $current_layout )
  18. $classes[] = 'left-sidebar';
  19. else
  20. $classes[] = $current_layout;
  21.  
  22. $classes = apply_filters( 'newtheme_layout_classes', $classes, $current_layout );
  23.  
  24. return array_merge( $existing_classes, $classes );
  25. }
  26. add_filter( 'body_class', 'newtheme_layout_classes' );

Esta función añade las clases correspondientes a la etiqueta body dependiendo de la estructura de blog elegida.

  1. <?php
  2.  
  3. /**
  4.  * Implements New Theme theme options into Theme Customizer
  5.  *
  6.  * @param $wp_customize Theme Customizer object
  7.  * @return void
  8.  */
  9. function newtheme_customize_register( $wp_customize ) {
  10. $wp_customize->get_setting( 'blogname' )->transport = 'postMessage';
  11. $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage';
  12.  
  13. $options = newtheme_get_theme_options();
  14. $defaults = newtheme_get_default_theme_options();
  15.  
  16. $wp_customize->add_setting( 'newtheme_theme_options[color_scheme]', array(
  17. 'default' => $defaults['color_scheme'],
  18. 'type' => 'option',
  19. 'capability' => 'edit_theme_options',
  20. ) );
  21.  
  22. $schemes = newtheme_color_schemes();
  23. $choices = array();
  24. foreach ( $schemes as $scheme ) {
  25. $choices[ $scheme['value'] ] = $scheme['label'];
  26. }
  27.  
  28. $wp_customize->add_control( 'newtheme_color_scheme', array(
  29. 'label' => __( 'Color Scheme', 'newtheme' ),
  30. 'section' => 'colors',
  31. 'settings' => 'newtheme_theme_options[color_scheme]',
  32. 'type' => 'radio',
  33. 'choices' => $choices,
  34. 'priority' => 5,
  35. ) );
  36.  
  37. // Link Color (added to Color Scheme section in Theme Customizer)
  38. $wp_customize->add_setting( 'newtheme_theme_options[link_color]', array(
  39. 'default' => newtheme_get_default_link_color( $options['color_scheme'] ),
  40. 'type' => 'option',
  41. 'sanitize_callback' => 'sanitize_hex_color',
  42. 'capability' => 'edit_theme_options',
  43. ) );
  44.  
  45. $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'link_color', array(
  46. 'label' => __( 'Link Color', 'newtheme' ),
  47. 'section' => 'colors',
  48. 'settings' => 'newtheme_theme_options[link_color]',
  49. ) ) );
  50.  
  51. // Default Layout
  52. $wp_customize->add_section( 'newtheme_layout', array(
  53. 'title' => __( 'Layout', 'newtheme' ),
  54. 'priority' => 50,
  55. ) );
  56.  
  57. $wp_customize->add_setting( 'newtheme_theme_options[theme_layout]', array(
  58. 'type' => 'option',
  59. 'default' => $defaults['theme_layout'],
  60. 'sanitize_callback' => 'sanitize_key',
  61. ) );
  62.  
  63. $layouts = newtheme_layouts();
  64. $choices = array();
  65. foreach ( $layouts as $layout ) {
  66. $choices[$layout['value']] = $layout['label'];
  67. }
  68.  
  69. $wp_customize->add_control( 'newtheme_theme_options[theme_layout]', array(
  70. 'section' => 'newtheme_layout',
  71. 'type' => 'radio',
  72. 'choices' => $choices,
  73. ) );
  74. }
  75. add_action( 'customize_register', 'newtheme_customize_register' );

Esta función añade todas las opciones al personalizador de temas.

  1. <?php
  2.  
  3. /**
  4.  * Bind JS handlers to make Theme Customizer preview reload changes asynchronously.
  5.  * Used with blogname and blogdescription.
  6.  */
  7. function newtheme_customize_preview_js() {
  8. wp_enqueue_script( 'newtheme-customizer', get_template_directory_uri() . '/inc/theme-customizer.js', array( 'customize-preview' ), '20120523', true );
  9. }
  10. add_action( 'customize_preview_init', 'newtheme_customize_preview_js' );

Esta función indica a WordPress que añada un archivo javascript para la previsualización de la página para poder ver los cambios del tema.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, functions.php

0

Como ya llevamos varias plantillas creadas con algunas llamadas a funciones del archivo functions.php, vamos a crearlo y añadir esas funciones, después continuaremos añadiendo más plantillas.

 

FUNCTIONS.PHP

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

  1. <?php
  2.  
  3. /**
  4.  * Set the content width based on the theme's design and stylesheet.
  5.  */
  6. if ( ! isset( $content_width ) )
  7. $content_width = 584;

Este código creara una variable que nos indicará el ancho que tendrá el contenido.

  1. <?php
  2.  
  3. /**
  4.  * Tell WordPress to run newtheme_setup() when the 'after_setup_theme' hook is run.
  5.  */
  6. add_action( 'after_setup_theme', 'newtheme_setup' );
  7.  
  8. if ( ! function_exists( 'newtheme_setup' ) ):
  9.  
  10. function newtheme_setup() {
  11.  
  12. }
  13.  
  14. endif;

 

Le decimos a WordPress que ejecute newtheme_setup cuando el hook after_setup_theme esté funcionando. Creamos un condicional para comprobar que la función newtheme_setup no ha sido aun creada, y creamos la función.

Dentro de newtheme_setup añadiremos las siguientes lineas de código:

  1. <?php
  2.  
  3. load_theme_textdomain( 'newtheme', get_template_directory() . '/languages' );

Esta línea cargará el archivo de idioma correspondiente.

  1. <?php
  2.  
  3. add_editor_style();

Le indicamos a WordPress que cargue el editor de estilos. Para ello WordPress buscará el archivo editor-style.css dentro de la carpeta del tema, por tanto copiaremos los archivos editor-style.css y editor-style-rtl.css del tema Twenty Eleven a nuestro tema.

  1. <?php
  2.  
  3. require( get_template_directory() . '/inc/theme-options.php' );
  4. require( get_template_directory() . '/inc/widgets.php' );

Estas dos lineas cargan los archivos de las opciones del tema que se mostrarán en la administración y los widgets de los que disponga el tema.

  1. <?php
  2.  
  3. add_theme_support( 'automatic-feed-links' );

Le indicamos a WordPress que los links de este tema se añadirán a un archivo rss que se creará automáticamente. Más sobre otros argumentos de esta función: http://codex.wordpress.org/Function_Reference/add_theme_support

  1. <?php
  2.  
  3. register_nav_menu( 'primary', __( 'Primary Menu', 'newtheme' ) );

Registramos la barra de menú de la cabecera.

  1. <?php
  2. add_theme_support( 'post-formats', array( 'aside', 'link', 'gallery', 'status', 'quote', 'image' ) );

Añadimos soporte para varios tipos de formato de posts.

  1. <?php
  2.  
  3. $theme_options = newtheme_get_theme_options();
  4. if ( 'dark' == $theme_options['color_scheme'] )
  5. $default_background_color = '1d1d1d';
  6. else
  7. $default_background_color = 'f1f1f1';
  8.  
  9. // Add support for custom backgrounds.
  10. add_theme_support( 'custom-background', array(
  11. // Let WordPress know what our default background color is.
  12. // This is dependent on our current color scheme.
  13. 'default-color' => $default_background_color,
  14. ) );

Primero recuperamos las opciones del tema a través de la función newtheme_get_theme_options(), que se encuentra en el archivo inc/theme_options.php, el cual crearemos más delante.

Comprobamos que tipo de esquema de estilos se ha elegido y guardamos en la variable $default_background_color el valor correspondiente.

Le indicamos a WordPress el color de nuestro fondo de página.

  1. <?php
  2.  
  3. add_theme_support( 'post-thumbnails' );

Le indicamos a WordPress que este tema utilizará imágenes destacadas o thumbnails.

  1. <?php
  2.  
  3. $custom_header_support = array(
  4. // The default header text color.
  5. 'default-text-color' => '000',
  6. // The height and width of our custom header.
  7. 'width' => apply_filters( 'newtheme_header_image_width', 1000 ),
  8. 'height' => apply_filters( 'newtheme_header_image_height', 288 ),
  9. // Support flexible heights.
  10. 'flex-height' => true,
  11. // Random image rotation by default.
  12. 'random-default' => true,
  13. // Callback for styling the header.
  14. 'wp-head-callback' => 'newtheme_header_style',
  15. // Callback for styling the header preview in the admin.
  16. 'admin-head-callback' => 'newtheme_admin_header_style',
  17. // Callback used to display the header preview in the admin.
  18. 'admin-preview-callback' => 'newtheme_admin_header_image',
  19. );
  20.  
  21. add_theme_support( 'custom-header', $custom_header_support );

Creamos un array con los encabezados personalizados y se lo indicamos a WordPress.

  1. <?php
  2.  
  3. if ( ! function_exists( 'get_custom_header' ) ) {
  4. // This is all for compatibility with versions of WordPress prior to 3.4.
  5. define( 'HEADER_TEXTCOLOR', $custom_header_support['default-text-color'] );
  6. define( 'HEADER_IMAGE', '' );
  7. define( 'HEADER_IMAGE_WIDTH', $custom_header_support['width'] );
  8. define( 'HEADER_IMAGE_HEIGHT', $custom_header_support['height'] );
  9. add_custom_image_header( $custom_header_support['wp-head-callback'], $custom_header_support['admin-head-callback'], $custom_header_support['admin-preview-callback'] );
  10. add_custom_background();
  11. }

En el caso de que se utilizase este tema con una versión de WordPress inferior a la 3.4 creamos varias constantes, y añadimos las cabeceras personalizadas y el fondo a WordPress.

  1. <?php
  2.  
  3. set_post_thumbnail_size( $custom_header_support['width'], $custom_header_support['height'], true );

Configuramos la imagen destacada definiendo un ancho y alto.

  1. <?php
  2.  
  3. add_image_size( 'large-feature', $custom_header_support['width'], $custom_header_support['height'], true );
  4. // Used for featured posts if a large-feature doesn't exist.
  5. add_image_size( 'small-feature', 500, 300 );

Añadimos la imagen a la cabecera definiendo su ancho y alto, además añadimos una imagen más pequeña para los post en el caso de que no existe imagen para la cabecera.

  1. <?php
  2.  
  3. register_default_headers( array(
  4. 'wheel' => array(
  5. 'url' => '%s/images/headers/wheel.jpg',
  6. 'thumbnail_url' => '%s/images/headers/wheel-thumbnail.jpg',
  7. /* translators: header image description */
  8. 'description' => __( 'Wheel', 'newtheme' )
  9. ),
  10. 'shore' => array(
  11. 'url' => '%s/images/headers/shore.jpg',
  12. 'thumbnail_url' => '%s/images/headers/shore-thumbnail.jpg',
  13. /* translators: header image description */
  14. 'description' => __( 'Shore', 'newtheme' )
  15. ),
  16. 'trolley' => array(
  17. 'url' => '%s/images/headers/trolley.jpg',
  18. 'thumbnail_url' => '%s/images/headers/trolley-thumbnail.jpg',
  19. /* translators: header image description */
  20. 'description' => __( 'Trolley', 'newtheme' )
  21. ),
  22. 'pine-cone' => array(
  23. 'url' => '%s/images/headers/pine-cone.jpg',
  24. 'thumbnail_url' => '%s/images/headers/pine-cone-thumbnail.jpg',
  25. /* translators: header image description */
  26. 'description' => __( 'Pine Cone', 'newtheme' )
  27. ),
  28. 'chessboard' => array(
  29. 'url' => '%s/images/headers/chessboard.jpg',
  30. 'thumbnail_url' => '%s/images/headers/chessboard-thumbnail.jpg',
  31. /* translators: header image description */
  32. 'description' => __( 'Chessboard', 'newtheme' )
  33. ),
  34. 'lanterns' => array(
  35. 'url' => '%s/images/headers/lanterns.jpg',
  36. 'thumbnail_url' => '%s/images/headers/lanterns-thumbnail.jpg',
  37. /* translators: header image description */
  38. 'description' => __( 'Lanterns', 'newtheme' )
  39. ),
  40. 'willow' => array(
  41. 'url' => '%s/images/headers/willow.jpg',
  42. 'thumbnail_url' => '%s/images/headers/willow-thumbnail.jpg',
  43. /* translators: header image description */
  44. 'description' => __( 'Willow', 'newtheme' )
  45. ),
  46. 'hanoi' => array(
  47. 'url' => '%s/images/headers/hanoi.jpg',
  48. 'thumbnail_url' => '%s/images/headers/hanoi-thumbnail.jpg',
  49. /* translators: header image description */
  50. 'description' => __( 'Hanoi Plant', 'newtheme' )
  51. )
  52. ) );

Este es el paquete de imágenes que el tema Twenty Eleven trae por defecto, nosotros haremos lo mismo. Si no lo habéis hecho ya, copiad la carpeta images del tema Twenty Eleven a nuestro tema.

El marcador %s indica que se debe sustituir por la uri del tema.

Como esta función tiene llamadas a otras funciones dentro del mismo archivo functions.php, vamos a crearlas.

En primer lugar crearemos la función newtheme_header_style():

  1. <?php
  2.  
  3. if ( ! function_exists( 'newtheme_header_style' ) ) :
  4. /**
  5.  * Styles the header image and text displayed on the blog
  6.  */
  7. function newtheme_header_style() {
  8. $text_color = get_header_textcolor();
  9.  
  10. // If no custom options for text are set, let's bail.
  11. if ( $text_color == HEADER_TEXTCOLOR )
  12. return;
  13.  
  14. // If we get this far, we have custom styles. Let's do this.
  15. ?>
  16. <style type="text/css">
  17. <?php
  18. // Has the text been hidden?
  19. if ( 'blank' == $text_color ) :
  20. ?>
  21. #site-title,
  22. #site-description {
  23. position: absolute !important;
  24. clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
  25. clip: rect(1px, 1px, 1px, 1px);
  26. }
  27. <?php
  28. // If the user has set a custom color for the text use that
  29. else :
  30. ?>
  31. #site-title a,
  32. #site-description {
  33. color: #<?php echo $text_color; ?> !important;
  34. }
  35. <?php endif; ?>
  36. </style>
  37. <?php
  38. }
  39. endif; // newtheme_header_style

Simplemente en esta función se generan los estilos para el título y la descripción que se ubican en la cabecera de la página.

Creamos el método newtheme_admin_header_style():

  1. <?php
  2.  
  3. if ( ! function_exists( 'newtheme_admin_header_style' ) ) :
  4. /**
  5.  * Styles the header image displayed on the Appearance > Header admin panel.
  6.  *
  7.  * Referenced via add_theme_support('custom-header') in newtheme_setup().
  8.  */
  9. function newtheme_admin_header_style() {
  10. ?>
  11. <style type="text/css">
  12. .appearance_page_custom-header #headimg {
  13. border: none;
  14. }
  15. #headimg h1,
  16. #desc {
  17. font-family: "Helvetica Neue", Arial, Helvetica, "Nimbus Sans L", sans-serif;
  18. }
  19. #headimg h1 {
  20. margin: 0;
  21. }
  22. #headimg h1 a {
  23. font-size: 32px;
  24. line-height: 36px;
  25. text-decoration: none;
  26. }
  27. #desc {
  28. font-size: 14px;
  29. line-height: 23px;
  30. padding: 0 0 3em;
  31. }
  32. <?php
  33. // If the user has set a custom color for the text use that
  34. if ( get_header_textcolor() != HEADER_TEXTCOLOR ) :
  35. ?>
  36. #site-title a,
  37. #site-description {
  38. color: #<?php echo get_header_textcolor(); ?>;
  39. }
  40. <?php endif; ?>
  41. #headimg img {
  42. max-width: 1000px;
  43. height: auto;
  44. width: 100%;
  45. }
  46. </style>
  47. <?php
  48. }
  49. endif; // newhtme_admin_header_style

Esta función permite dar estilos a la imagen de la cabecera dentro de su apartado de opciones en la administración de WordPress, donde se podrá configurar cómo se ve la imagen.

Creamos la función newtheme_admin_header_image():

  1. <?php
  2.  
  3. if ( ! function_exists( 'newtheme_admin_header_image' ) ) :
  4. /**
  5.  * Custom header image markup displayed on the Appearance > Header admin panel.
  6.  *
  7.  * Referenced via add_theme_support('custom-header') in newtheme_setup().
  8.  */
  9. function newtheme_admin_header_image() { ?>
  10. <div id="headimg">
  11. <?php
  12. $color = get_header_textcolor();
  13. $image = get_header_image();
  14. if ( $color && $color != 'blank' )
  15. $style = ' style="color:#' . $color . '"';
  16. else
  17. $style = ' style="display:none"';
  18. ?>
  19. <h1><a id="name"<?php echo $style; ?> onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1>
  20. <div id="desc"<?php echo $style; ?>><?php bloginfo( 'description' ); ?></div>
  21. <?php if ( $image ) : ?>
  22. <img src="<?php echo esc_url( $image ); ?>" alt="" />
  23. <?php endif; ?>
  24. </div>
  25. <?php }
  26. endif; // newtheme_admin_header_image

Esta función crea el código html que mostrará la imagen, el título y la descripción en su respectiva zona de opciones de la administración de WordPress, para que el usuario pueda ver como quedaría.

  1. <?php
  2.  
  3. /**
  4.  * Sets the post excerpt length to 40 words.
  5.  *
  6.  * To override this length in a child theme, remove the filter and add your own
  7.  * function tied to the excerpt_length filter hook.
  8.  */
  9. function newtheme_excerpt_length( $length ) {
  10. return 40;
  11. }
  12. add_filter( 'excerpt_length', 'newtheme_excerpt_length' );

Esta función establece la longitud del extracto de un post a 40 palabras.

  1. <?php
  2.  
  3. /**
  4.  * Returns a "Continue Reading" link for excerpts
  5.  */
  6. function newtheme_continue_reading_link() {
  7. return ' <a href="'. esc_url( get_permalink() ) . '">' . __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'newtheme' ) . '</a>';
  8. }

Esta función devuelve el link con el texto «Seguir leyendo…» en los extractos de los posts.

  1. <?php
  2.  
  3. /**
  4.  * Replaces "[...]" (appended to automatically generated excerpts) with an ellipsis and newtheme_continue_reading_link().
  5.  *
  6.  * To override this in a child theme, remove the filter and add your own
  7.  * function tied to the excerpt_more filter hook.
  8.  */
  9. function newtheme_auto_excerpt_more( $more ) {
  10. return ' &hellip;' . newtheme_continue_reading_link();
  11. }
  12. add_filter( 'excerpt_more', 'newtheme_auto_excerpt_more' );

Esta función remplaza el texto «[…]» por «…» utilizando «&hellip;» para ello, y el link de newtheme_continue_reading_link()

  1. <?php
  2.  
  3. /**
  4.  * Adds a pretty "Continue Reading" link to custom post excerpts.
  5.  *
  6.  * To override this link in a child theme, remove the filter and add your own
  7.  * function tied to the get_the_excerpt filter hook.
  8.  */
  9. function newtheme_custom_excerpt_more( $output ) {
  10. if ( has_excerpt() && ! is_attachment() ) {
  11. $output .= newtheme_continue_reading_link();
  12. }
  13. return $output;
  14. }
  15. add_filter( 'get_the_excerpt', 'newtheme_custom_excerpt_more' );

Añade la salida de newtheme_continue_reading_link() a los extractos personalizados de los posts.

  1. <?php
  2.  
  3. /**
  4.  * Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link.
  5.  */
  6. function newtheme_page_menu_args( $args ) {
  7. $args['show_home'] = true;
  8. return $args;
  9. }
  10. add_filter( 'wp_page_menu_args', 'newtheme_page_menu_args' );

Esta función hace que en nuestro menú de navegación aparezca un link hacía la página principal.

  1. <?php
  2.  
  3. /**
  4.  * Register our sidebars and widgetized areas. Also register the default Epherma widget.
  5.  */
  6. function newtheme_widgets_init() {
  7.  
  8. register_widget( 'New_Theme_Ephemera_Widget' );
  9.  
  10. register_sidebar( array(
  11. 'name' => __( 'Main Sidebar', 'newtheme' ),
  12. 'id' => 'sidebar-1',
  13. 'before_widget' => '<aside id="%1$s" class="widget %2$s">',
  14. 'after_widget' => "</aside>",
  15. 'before_title' => '<h3 class="widget-title">',
  16. 'after_title' => '</h3>',
  17. ) );
  18.  
  19. register_sidebar( array(
  20. 'name' => __( 'Showcase Sidebar', 'newtheme' ),
  21. 'id' => 'sidebar-2',
  22. 'description' => __( 'The sidebar for the optional Showcase Template', 'newtheme' ),
  23. 'before_widget' => '<aside id="%1$s" class="widget %2$s">',
  24. 'after_widget' => "</aside>",
  25. 'before_title' => '<h3 class="widget-title">',
  26. 'after_title' => '</h3>',
  27. ) );
  28.  
  29. register_sidebar( array(
  30. 'name' => __( 'Footer Area One', 'newtheme' ),
  31. 'id' => 'sidebar-3',
  32. 'description' => __( 'An optional widget area for your site footer', 'newtheme' ),
  33. 'before_widget' => '<aside id="%1$s" class="widget %2$s">',
  34. 'after_widget' => "</aside>",
  35. 'before_title' => '<h3 class="widget-title">',
  36. 'after_title' => '</h3>',
  37. ) );
  38.  
  39. register_sidebar( array(
  40. 'name' => __( 'Footer Area Two', 'newtheme' ),
  41. 'id' => 'sidebar-4',
  42. 'description' => __( 'An optional widget area for your site footer', 'newtheme' ),
  43. 'before_widget' => '<aside id="%1$s" class="widget %2$s">',
  44. 'after_widget' => "</aside>",
  45. 'before_title' => '<h3 class="widget-title">',
  46. 'after_title' => '</h3>',
  47. ) );
  48.  
  49. register_sidebar( array(
  50. 'name' => __( 'Footer Area Three', 'newtheme' ),
  51. 'id' => 'sidebar-5',
  52. 'description' => __( 'An optional widget area for your site footer', 'newtheme' ),
  53. 'before_widget' => '<aside id="%1$s" class="widget %2$s">',
  54. 'after_widget' => "</aside>",
  55. 'before_title' => '<h3 class="widget-title">',
  56. 'after_title' => '</h3>',
  57. ) );
  58. }
  59. add_action( 'widgets_init', 'newtheme_widgets_init' );

Esta función registra nuestro widget que crearemos en el archivo inc/widgets.php, y las cinco sidebars que añade el tema a diferentes partes de la página.

  1. <?php
  2.  
  3. if ( ! function_exists( 'newtheme_content_nav' ) ) :
  4. /**
  5.  * Display navigation to next/previous pages when applicable
  6.  */
  7. function newtheme_content_nav( $nav_id ) {
  8. global $wp_query;
  9.  
  10. if ( $wp_query->max_num_pages > 1 ) : ?>
  11. <nav id="<?php echo $nav_id; ?>">
  12. <h3 class="assistive-text"><?php _e( 'Post navigation', 'newtheme' ); ?></h3>
  13. <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'newtheme' ) ); ?></div>
  14. <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?></div>
  15. </nav><!-- #nav-above -->
  16. <?php endif;
  17. }
  18. endif; // newtheme_content_nav

Muestra los links para mostrar la siguiente o anterior página de posts cuando sea aplicable.

  1. <?php
  2.  
  3. /**
  4.  * Return the URL for the first link found in the post content.
  5.  *
  6.  * @return string|bool URL or false when no link is present.
  7.  */
  8. function newtheme_url_grabber() {
  9. if ( ! preg_match( '/<a\s[^>]*?href=[\'"](.+?)[\'"]/is', get_the_content(), $matches ) )
  10. return false;
  11.  
  12. return esc_url_raw( $matches[1] );
  13. }

Devuelve la url del primer link encontrado en el contenido del post.

  1. <?php
  2.  
  3. /**
  4.  * Count the number of footer sidebars to enable dynamic classes for the footer
  5.  */
  6. function newtheme_footer_sidebar_class() {
  7. $count = 0;
  8.  
  9. if ( is_active_sidebar( 'sidebar-3' ) )
  10. $count++;
  11.  
  12. if ( is_active_sidebar( 'sidebar-4' ) )
  13. $count++;
  14.  
  15. if ( is_active_sidebar( 'sidebar-5' ) )
  16. $count++;
  17.  
  18. $class = '';
  19.  
  20. switch ( $count ) {
  21. case '1':
  22. $class = 'one';
  23. break;
  24. case '2':
  25. $class = 'two';
  26. break;
  27. case '3':
  28. $class = 'three';
  29. break;
  30. }
  31.  
  32. if ( $class )
  33. echo 'class="' . $class . '"';
  34. }

Cuenta el número de sidebars habilitados para el pie de página y devuelve la clase que corresponda.

  1. <?php
  2.  
  3. if ( ! function_exists( 'newtheme_comment' ) ) :
  4. /**
  5.  * Template for comments and pingbacks.
  6.  *
  7.  * To override this walker in a child theme without modifying the comments template
  8.  * simply create your own newtheme_comment(), and that function will be used instead.
  9.  *
  10.  * Used as a callback by wp_list_comments() for displaying the comments.
  11.  *
  12.  */
  13. function newtheme_comment( $comment, $args, $depth ) {
  14. $GLOBALS['comment'] = $comment;
  15. switch ( $comment->comment_type ) :
  16. case 'pingback' :
  17. case 'trackback' :
  18. ?>
  19. <li class="post pingback">
  20. <p><?php _e( 'Pingback:', 'newtheme' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?></p>
  21. <?php
  22. break;
  23. default :
  24. ?>
  25. <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>">
  26. <article id="comment-<?php comment_ID(); ?>" class="comment">
  27. <footer class="comment-meta">
  28. <div class="comment-author vcard">
  29. <?php
  30. $avatar_size = 68;
  31. if ( '0' != $comment->comment_parent )
  32. $avatar_size = 39;
  33.  
  34. echo get_avatar( $comment, $avatar_size );
  35.  
  36. /* translators: 1: comment author, 2: date and time */
  37. printf( __( '%1$s on %2$s <span class="says">said:</span>', 'newtheme' ),
  38. sprintf( '<span class="fn">%s</span>', get_comment_author_link() ),
  39. sprintf( '<a href="%1$s"><time pubdate datetime="%2$s">%3$s</time></a>',
  40. esc_url( get_comment_link( $comment->comment_ID ) ),
  41. get_comment_time( 'c' ),
  42. /* translators: 1: date, 2: time */
  43. sprintf( __( '%1$s at %2$s', 'newtheme' ), get_comment_date(), get_comment_time() )
  44. )
  45. );
  46. ?>
  47.  
  48. <?php edit_comment_link( __( 'Edit', 'newtheme' ), '<span class="edit-link">', '</span>' ); ?>
  49. </div><!-- .comment-author .vcard -->
  50.  
  51. <?php if ( $comment->comment_approved == '0' ) : ?>
  52. <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'newtheme' ); ?></em>
  53. <br />
  54. <?php endif; ?>
  55.  
  56. </footer>
  57.  
  58. <div class="comment-content"><?php comment_text(); ?></div>
  59.  
  60. <div class="reply">
  61. <?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply <span>&darr;</span>', 'newtheme' ), 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
  62. </div><!-- .reply -->
  63. </article><!-- #comment-## -->
  64.  
  65. <?php
  66. break;
  67. endswitch;
  68. }
  69. endif; // ends check for newtheme_comment()

Esta función genera el código html necesario para mostrar cada comentario de un post.

  1. <?php
  2.  
  3. if ( ! function_exists( 'newtheme_posted_on' ) ) :
  4. /**
  5.  * Prints HTML with meta information for the current post-date/time and author.
  6.  * Create your own newtheme_posted_on to override in a child theme
  7.  */
  8. function newtheme_posted_on() {
  9. printf( __( '<span class="sep">Posted on </span><a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s" pubdate>%4$s</time></a><span class="by-author"> <span class="sep"> by </span> <span class="author vcard"><a class="url fn n" href="%5$s" title="%6$s" rel="author">%7$s</a></span></span>', 'newtheme' ),
  10. esc_url( get_permalink() ),
  11. esc_attr( get_the_time() ),
  12. esc_attr( get_the_date( 'c' ) ),
  13. esc_html( get_the_date() ),
  14. esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ),
  15. esc_attr( sprintf( __( 'View all posts by %s', 'newtheme' ), get_the_author() ) ),
  16. get_the_author()
  17. );
  18. }
  19. endif;

Esta función devuelve los metadatos de un post.

  1. <?php
  2.  
  3. /**
  4.  * Adds two classes to the array of body classes.
  5.  * The first is if the site has only had one author with published posts.
  6.  * The second is if a singular post being displayed
  7.  */
  8. function newtheme_body_classes( $classes ) {
  9.  
  10. if ( function_exists( 'is_multi_author' ) && ! is_multi_author() )
  11. $classes[] = 'single-author';
  12.  
  13. if ( is_singular() && ! is_home() && ! is_page_template( 'showcase.php' ) && ! is_page_template( 'sidebar-page.php' ) )
  14. $classes[] = 'singular';
  15.  
  16. return $classes;
  17. }
  18. add_filter( 'body_class', 'newtheme_body_classes' );

Esta función devuelve las clases de estilos que corresponden para la etiqueta body dependiendo del tipo de página que se muestre al usuario.

Cron Job WordPress

WordPress 3.x para desarrolladores: Temas y plantillas, single.php y comments.php

0

Vamos con dos plantillas más, esta vez las que generan la página del post (single.php) y la de los comentarios (comment.php).

 

SINGLE.PHP

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

  1. <?php get_header(); ?>
  2.  
  3. <div id="primary">
  4. <div id="content" role="main">
  5.  
  6. <?php while ( have_posts() ) : the_post(); ?>
  7.  
  8. <nav id="nav-single">
  9. <h3 class="assistive-text"><?php _e( 'Post navigation', 'newtheme' ); ?></h3>
  10. <span class="nav-previous"><?php previous_post_link( '%link', __( '<span class="meta-nav">&larr;</span> Previous', 'newtheme' ) ); ?></span>
  11. <span class="nav-next"><?php next_post_link( '%link', __( 'Next <span class="meta-nav">&rarr;</span>', 'newtheme' ) ); ?></span>
  12. </nav><!-- #nav-single -->
  13.  
  14. <?php get_template_part( 'content', 'single' ); ?>
  15.  
  16. <?php comments_template( '', true ); ?>
  17.  
  18. <?php endwhile; // end of the loop. ?>
  19.  
  20. </div><!-- #content -->
  21. </div><!-- #primary -->
  22.  
  23. <?php get_footer(); ?>

Como puedes ver la estructura de este archivo es muy parecida a la de index.php, tenemos una llamada get_header() para crear la cabecera y otra a get_footer() para crear el pie. En medio encontramos el bloque que generará el html para mostrar el post. Tenemos el mismo bucle que teníamos en la página principal además de dos funciones que generan los links hacia el post anterior y el posterior: previous_post_link() y next_post_link().

Se hace una llamada a get_template_part() que cargará la plantilla content-single.php.

Por último carga la plantilla de comentarios con la función comments_template().

 

COMMENTS.PHP

Crea el archivo comments.php y añade el siguiente código:

 

 

  1. <div id="comments">
  2. <?php if ( post_password_required() ) : ?>
  3. <p class="nopassword"><?php _e( 'This post is password protected. Enter the password to view any comments.', 'newtheme' ); ?></p>
  4. </div><!-- #comments -->
  5. <?php
  6. /* Stop the rest of comments.php from being processed,
  7. * but don't kill the script entirely -- we still have
  8. * to fully load the template.
  9. */
  10. return;
  11. endif;
  12. ?>
  13.  
  14. <?php // You can start editing here -- including this comment! ?>
  15.  
  16. <?php if ( have_comments() ) : ?>
  17. <h2 id="comments-title">
  18. <?php
  19. printf( _n( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'newtheme' ),
  20. number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
  21. ?>
  22. </h2>
  23.  
  24. <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
  25. <nav id="comment-nav-above">
  26. <h1 class="assistive-text"><?php _e( 'Comment navigation', 'newtheme' ); ?></h1>
  27. <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'newtheme' ) ); ?></div>
  28. <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'newtheme' ) ); ?></div>
  29. </nav>
  30. <?php endif; // check for comment navigation ?>
  31.  
  32. <ol class="commentlist">
  33. <?php
  34. /* Loop through and list the comments. Tell wp_list_comments()
  35. * to use newtheme_comment() to format the comments.
  36. * If you want to overload this in a child theme then you can
  37. * define newtheme_comment() and that will be used instead.
  38. * See newtheme_comment() in newytheme/functions.php for more.
  39. */
  40. wp_list_comments( array( 'callback' => 'newtheme_comment' ) );
  41. ?>
  42. </ol>
  43.  
  44. <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
  45. <nav id="comment-nav-below">
  46. <h1 class="assistive-text"><?php _e( 'Comment navigation', 'newtheme' ); ?></h1>
  47. <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'newtheme' ) ); ?></div>
  48. <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'newtheme' ) ); ?></div>
  49. </nav>
  50. <?php endif; // check for comment navigation ?>
  51.  
  52. <?php
  53. /* If there are no comments and comments are closed, let's leave a little note, shall we?
  54. * But we don't want the note on pages or post types that do not support comments.
  55. */
  56. elseif ( ! comments_open() && ! is_page() && post_type_supports( get_post_type(), 'comments' ) ) :
  57. ?>
  58. <p class="nocomments"><?php _e( 'Comments are closed.', 'newtheme' ); ?></p>
  59. <?php endif; ?>
  60.  
  61. <?php comment_form(); ?>
  62.  
  63. </div><!-- #comments -->

 

Vamos a ver este código poco a poco:

  1. <div id="comments">
  2. <?php if ( post_password_required() ) : ?>
  3. <p class="nopassword"><?php _e( 'This post is password protected. Enter the password to view any comments.', 'newtheme' ); ?></p>
  4. </div><!-- #comments -->
  5. <?php
  6. /* Stop the rest of comments.php from being processed,
  7. * but don't kill the script entirely -- we still have
  8. * to fully load the template.
  9. */
  10. return;
  11. endif;
  12. ?>

 

En primer lugar comprobamos si los comentarios están protegidos por contraseña, si es así se devuelve un return, que evitará que el resto de la plantilla se procese, pero se continuará ejecutando el script.

En el caso de que los comentarios no estén protegidos por contraseña, se comprueba que el post tenga comentarios utilizando la función have_comments(), si es que sí los tiene se genera el html correspondiente.

  1. <?php if ( have_comments() ) : ?>
  2. <h2 id="comments-title">
  3. <?php
  4. printf( _n( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'newtheme' ),
  5. number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' );
  6. ?>
  7. </h2>

Como ves, aquí se comprueba si hay comentarios, en caso positivo se crea la cabecera de los comentarios.

  1. <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
  2. <nav id="comment-nav-above">
  3. <h1 class="assistive-text"><?php _e( 'Comment navigation', 'newtheme' ); ?></h1>
  4. <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'newtheme' ) ); ?></div>
  5. <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'newtheme' ) ); ?></div>
  6. </nav>
  7. <?php endif; // check for comment navigation ?>

Se crea el sistema de navegación de los comentarios, para mostrar los comentarios más recientes o los más antiguos.

  1. <ol class="commentlist">
  2. <?php
  3. /* Loop through and list the comments. Tell wp_list_comments()
  4. * to use newtheme_comment() to format the comments.
  5. * If you want to overload this in a child theme then you can
  6. * define newtheme_comment() and that will be used instead.
  7. * See newtheme_comment() in newytheme/functions.php for more.
  8. */
  9. wp_list_comments( array( 'callback' => 'newtheme_comment' ) );
  10. ?>
  11. </ol>

Añadimos los comentarios utilizando una llamada a wp_list_comments(), en el que se indica que procese los datos de los comentarios utilizando la función newtheme_comment que encontrará en el archivo functions.php.

Para ver otros argumentos que se le pueden indicar a la función wp_list_comments() ver http://codex.wordpress.org/Function_Reference/wp_list_comments

  1. <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?>
  2. <nav id="comment-nav-below">
  3. <h1 class="assistive-text"><?php _e( 'Comment navigation', 'newtheme' ); ?></h1>
  4. <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'newtheme' ) ); ?></div>
  5. <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'newtheme' ) ); ?></div>
  6. </nav>
  7. <?php endif; // check for comment navigation ?>

Volvemos a crear el sistema de navegación de los comentarios, pero esta vez al finalizar la lista de comentarios.

  1. <?php
  2. /* If there are no comments and comments are closed, let's leave a little note, shall we?
  3. * But we don't want the note on pages or post types that do not support comments.
  4. */
  5. elseif ( ! comments_open() && ! is_page() && post_type_supports( get_post_type(), 'comments' ) ) :
  6. ?>
  7. <p class="nocomments"><?php _e( 'Comments are closed.', 'newtheme' ); ?></p>
  8. <?php endif; ?>
  9.  
  10. <?php comment_form(); ?>
  11.  
  12. </div><!-- #comments -->

Por último mostramos un mensaje en el caso de que los comentarios estén cerrados, además, mostramos el formulario para enviar un comentario.

Ir arriba