Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Copa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Cómo crear plantillas personalizadas para una entrada en WordPress

Nota editorial: Ganamos una comisión de los enlaces de socios en WPBeginner. Las comisiones no afectan a las opiniones o evaluaciones de nuestros editores. Más información sobre Proceso editorial.

¿Desea crear una plantilla personalizada para una sola entrada en WordPress?

Las plantillas personalizadas para entradas individuales te permiten utilizar diferentes disposiciones para cada una de las entradas de tu blog. Muchos temas de WordPress vienen con diferentes plantillas de página, y también puedes crear las tuyas propias si lo necesitas.

En este artículo, te mostraremos cómo crear fácilmente plantillas personalizadas para una sola entrada en WordPress. Compartiremos varios métodos para que puedas elegir el que mejor se adapte a tus necesidades.

How to Create Custom Single Post Templates in WordPress

¿Cuándo necesita una plantilla de entrada única personalizada?

A veces es posible que desee un aspecto diferente para ciertas entradas en su sitio web de WordPress. Por ejemplo, es posible que desee utilizar una estructura / disposición / diseño / plantilla diferente para los artículos destacados o historias en una categoría en particular.

Aquí es donde usted necesita una plantilla de entrada única personalizada en WordPress.

Por defecto, WordPress utiliza la plantilla de una sola entrada basada en la jerarquía de plantillas de WordPress. Todos los temas incluyen una plantilla single.php, que se utiliza por defecto para todas las entradas individuales.

Algunos temas también pueden incluir plantillas adicionales u opciones de disposición que puede utilizar.

Es muy parecido a crear una plantilla de página personalizada. La mayoría de los temas de WordPress también vienen con plantillas de página que puede utilizar al editar una entrada o página en WordPress.

Choosing a Page Template

Dicho esto, veamos cómo crear fácilmente plantillas personalizadas para una sola entrada en WordPress. Te mostraremos múltiples métodos, para que puedas usar el que mejor te funcione.

Creación de plantillas de entradas individuales con el editor de bloques

Este método no crea realmente una plantilla de entrada y su flexibilidad es limitada. Sin embargo, es la forma más sencilla de guardar tus propias disposiciones / diseño / plantillas de entradas y reutilizarlas.

El editor de bloques por defecto de WordPress viene con una característica incorporada que permite guardar o reutilizar bloques. Uno de estos bloques reutilizables es el bloque de grupo.

El bloque de grupo permite agrupar varios bloques y plantillas de entradas enteras. A continuación, puede guardar este bloque de grupo y reutilizarlo en otras entradas.

Veamos cómo utilizar el bloque de grupo para guardar las plantillas de entradas personalizadas.

En primer lugar, debe crear una nueva entrada en WordPress. Después, simplemente añade un bloque de grupo al área de contenido.

Add Group Block

Ahora puede empezar a añadir bloques en el bloque de grupo para crear una única disposición de entradas para su blog de WordPress.

Puedes añadir los bloques que quieras, como columnas, medios y texto, imágenes de portada y mucho más.

Add Blocks to the Group

Cuando esté satisfecho con la estructura / disposición / diseño / plantilla que ha creado, suba el ratón y seleccione el bloque de grupo.

Basta con hacer clic en el icono del menú de tres puntos y seleccionar la opción “Añadir a bloques reutilizables”.

Add Reusable Block

A continuación, debe dar un nombre al bloque reutilizable y hacer clic en el botón Guardar. WordPress guardará su bloque reutilizable incluyendo todos los bloques dentro del bloque de grupo.

A continuación, puedes editar cualquier entrada existente en tu sitio web o crear una nueva. En la pantalla de edición de entradas, basta con hacer clic en el botón añadir nuevo bloque y buscar el bloque guardado en la pestaña “Reutilizable”.

Reuse Block

Añade el bloque a tu entrada y WordPress cargará todo tu bloque de grupo con todos los bloques y ajustes tal y como los guardaste.

Este método le permite guardar sus estructuras / disposiciones / diseño / plantillas personalizadas. Sin embargo, no le permite cambiar la forma en que el tema gestiona las entradas individuales.

Si desea una mayor flexibilidad, continúe leyendo el paso siguiente.

Creación de plantillas personalizadas para entradas individuales con SeedProd

La forma más fácil de crear una plantilla de entrada única personalizada es mediante el uso de SeedProd. Es el mejor plugin de WordPress sitio web maquetador y puede crear hermosas disposiciones del sitio web y plantillas personalizadas sin escribir ningún código.

Puede utilizar el maquetador de arrastrar y soltar de SeedProd para crear un tema de WordPress totalmente personalizado, incluidas plantillas personalizadas de una sola entrada.

Lo primero que tienes que hacer es instalar y activar el plugin SeedProd. Para más detalles, consulte nuestra guía paso a paso sobre cómo instalar un plugin de WordPress.

Tras la activación, deberá introducir su clave de licencia. Encontrará esta información en su cuenta del sitio web de SeedProd.

SeedProd license key

Después de eso, es hora de crear un tema de WordPress personalizado. Esto es mucho más sencillo de lo que parece.

Crear un tema de WordPress personalizado

En primer lugar, debe dirigirse a la página del maquetador de temas de SeedProd. Aquí, utilizarás uno de los temas de SeedProd como punto de partida. Esto reemplazará su tema de WordPress existente con un nuevo diseño personalizado.

Puede hacerlo al hacer clic en el botón “Temas”.

Create your custom theme

Se le mostrará una lista de temas de diseño profesional pensados para distintos tipos de sitios web. Por ejemplo, hay plantillas denominadas “Empresa moderna”, “Agencia de marketing” y “Tema de agente hipotecario”.

Eche un vistazo a las opciones y seleccione la que mejor se adapte a sus necesidades al hacer clic en el icono de la marca de verificación.

Select a Theme That Matches Your Needs

Una vez que haya elegido un tema, SeedProd generará todas las plantillas de temas que necesite, incluyendo una para páginas individuales y otra para entradas individuales.

Cada plantilla viene establecida con atractivas disposiciones y marcadores de posición de contenido que son fáciles de personalizar.

SeedProd Creates All the Templates You Need for Your Theme

Para saber más acerca de cómo crear un tema con SeedProd, consulte nuestra guía sobre cómo crear fácilmente un tema de WordPress personalizado sin ningún código.

Personalización de la plantilla por defecto de una sola entrada

SeedProd facilita la personalización de la plantilla ‘Single Post’ por defecto mediante un maquetador de arrastrar y soltar.

Simplemente haga clic en el enlace “Editar diseño” que se encuentra debajo de la plantilla. Esto abrirá su plantilla de entrada en el editor visual de SeedProd.

Click the 'Edit Design' Link Under the Single Post Template

El editor visual de SeedProd tiene una estructura / disposición / diseño / plantilla de 2 columnas. A la izquierda, encontrarás bloques y secciones que puedes añadir a tu diseño. Y a la derecha hay una vista previa de la plantilla donde puede ver sus cambios en tiempo real.

SeedProd Visual Editor Blocks and Sections

También es fácil personalizar la estructura / disposición / diseño / plantilla de tu entrada. Basta con hacer clic en cualquier bloque para ver sus ajustes en la columna de la izquierda.

Por ejemplo, si haces clic en el título de la entrada, podrás ver sus ajustes. Ahora puedes cambiar la alineación, el tamaño de la fuente, el nivel del encabezado, etc.

Click on a Block to Change Its Settings

Al hacer clic en la pestaña Avanzado podrás cambiar los colores de las fuentes, el espaciado y otros estilos.

Puede añadir bloques adicionales arrastrándolos desde la columna izquierda a la columna de vista previa. SeedProd utiliza etiquetas de plantilla para extraer contenido dinámico como títulos de entradas, imágenes destacadas, comentarios y más. Esto le permite añadir contenido a la plantilla sin tener que editar cada entrada individualmente.

Por ejemplo, puedes añadir un bloque de entradas al final del contenido de tu entrada. Esto mostrará entradas recientes que tus visitantes pueden desear leer cuando terminen la entrada actual. Este bloque se mostrará automáticamente en todas las entradas que utilicen esta plantilla.

Add a Posts Block to the Bottom of Your Single Posts Template

A continuación, puedes cambiar los ajustes del bloque Entradas para personalizar el contenido que se muestra.

Por ejemplo, puede mostrar contenido de categorías específicas, utilizar una disposición a dos columnas y cambiar el número de entradas que se muestran.

SeedProd Posts Block Settings

No dudes en pasar tiempo experimentando con distintos bloques y explorando sus ajustes.

Después de crear algo que te gustaría usar como plantilla de entrada, es hora de guardarlo al hacer clic en el botón verde ‘Guardar’ en la esquina superior derecha. Después de eso, puede cerrar el editor visual SeedProd al hacer clic en el icono de cierre ‘X’.

When You're Finished, Save the Single Post Template

Puedes personalizar el resto de tu tema de WordPress de la misma manera. Pero si necesitas un poco de ayuda, entonces vuelve a consultar nuestra guía paso a paso sobre cómo crear un tema de WordPress personalizado con SeedProd.

Cuando esté satisfecho con el aspecto, asegúrese de que el conmutador “Activar tema SeedProd” está en la posición de encendido. Su sitio de WordPress utilizará ahora su tema SeedProd y su plantilla personalizada para una sola entrada.

Enable the SeedProd Theme

Uso de los ajustes del tema para crear disposiciones personalizadas de una sola entrada

Muchos temas populares de WordPress vienen con ajustes incorporados para personalizar la apariencia de la plantilla de una sola entrada.

Si tu tema es compatible con estos ajustes, podrás encontrarlos en la pantalla de edición de entradas. Las opciones disponibles pueden cambiar dependiendo del tema que estés utilizando.

Por ejemplo, el tema Astra ofrece opciones de personalización al editar una sola entrada. Con estas opciones, puedes cambiar las barras laterales, ocultar cabeceras, títulos, menús y mucho más.

Astra Theme Single Post Template Customization

Por otro lado, muchos de los mejores temas de WordPress incluyen plantillas listas para usar.

Si tu tema incluye plantillas de entradas individuales, las encontrarás en el panel ‘Plantilla’ o ‘Atributos de la entrada’ mientras editas una entrada.

Choosing a Template When Writing a Single Post

Estas plantillas son disposiciones completas que puede utilizar sin necesidad de configuración.

Creación manual de plantillas de entradas únicas personalizadas con código

Este método es un poco avanzado, ya que requiere editar archivos de tema, copiar y pegar código y, opcionalmente, añadir CSS personalizado. Si no has hecho esto antes, entonces marca / comprueba nuestro tutorial sobre cómo copiar y pegar código en WordPress.

En primer lugar, debes abrir un editor de texto plano en tu ordenador, como el Bloc de Notas, y pegar en él el siguiente código:

<?php
/*
 * Template Name: Featured Article
 * Template Post Type: post, page, product
 */
  
 get_header();  ?>

Este código define una nueva plantilla llamada “Artículo destacado” y la pone a disposición de los tipos de entradas de página, entrada y producto.

Debe guardar este archivo como wpb-single-post.php en su escritorio. A continuación, debe añadir la plantilla a su sitio de WordPress. Para ello, debe utilizar un cliente FTP para subir el archivo a la carpeta de su tema actual.

Ahora puedes acceder a tu área de administrador de WordPress y crear o editar una entrada. Desplázate un poco hacia abajo en la pantalla de edición de entradas y verás un nuevo panel de “Plantilla” o caja meta de “Atributos de la entrada” con una opción para seleccionar la plantilla.

Select Your Custom Post Template

Verá que su plantilla personalizada de “Artículo destacado” aparece allí.

En este momento su plantilla está esencialmente vacía, por lo que al seleccionarla simplemente aparecerá una pantalla en blanco.

Vamos a corregir esto.

La forma más sencilla de hacerlo es copiar el código del archivo single.php de tu tema y utilizarlo como punto de partida. Tendrás que abrir el archivo single.php y copiar todo lo que hay después de la línea get_header().

A continuación, tienes que pegar este código al final de tu archivo wpb-single-post.php. Ahora puedes guardar o ahorrar este archivo y subirlo de nuevo a tu servidor.

Sin embargo, el aspecto será exactamente el mismo que el de su plantilla de entrada única actual. Ahora puede empezar a realizar cambios en su plantilla de entrada única personalizada.

Puede añadir sus propias clases CSS personalizadas, quitar barras laterales, crear una plantilla de ancho completo o lo que desee.

Creación de plantillas personalizadas de una sola entrada por categoría

¿Le gustaría utilizar una plantilla personalizada para una sola entrada basada en categorías? Por ejemplo, puedes dar a las entradas de la categoría de viajes una estructura / disposición / diseño / plantilla diferente a las entradas de la categoría de fotografía.

Puede hacerlo utilizando el maquetador de temas SeedProd o código.

Creación de plantillas personalizadas de una sola entrada por categoría con SeedProd

Anteriormente cubrimos cómo personalizar la plantilla de una sola entrada por defecto del Maquetador de Temas SeedProd. Pero no se detiene ahí. Con SeedProd puede añadir tantas plantillas de entradas personalizadas como desee, como una disposición diferente para cada categoría de entrada.

Para añadir una nueva plantilla de entrada única, simplemente enlaza el enlace ‘Duplicar’ bajo la plantilla de entrada original. Se creará una nueva plantilla llamada “Entrada única – Copia” y se añadirá a la parte superior de la página de plantillas de temas.

Create a New Post Template by Duplicating the Default Post Template

Puede personalizar la nueva plantilla de la misma manera que personalizó la plantilla por defecto de una sola entrada anteriormente. Simplemente enlaza el enlace ‘Editar Diseño’ de la plantilla y realiza los cambios que desees utilizando el editor visual de SeedProd.

Cuando haya terminado de personalizar la plantilla, tendrá que añadir algunas condiciones para que SeedProd sepa qué entradas deben utilizar esta plantilla. En este caso, queremos que se muestre al ver entradas dentro de una misma categoría.

Click the 'Edit Conditions' Link

Para ello, al hacer clic en el enlace “Editar condiciones” de la plantilla, se enlazará una nueva ventana emergente.

Aquí puede dar a la plantilla un nombre y una prioridad. La plantilla por defecto de una sola entrada tiene una prioridad de 0, así que asegúrese de dar a esta plantilla una prioridad más alta para que se muestre en las categorías coincidentes.

Add Conditions to Display the Template for a Certain Category

En “Condiciones”, selecciona “Tiene categoría” en el segundo menú desplegable y escribe el nombre de la categoría en el último campo. Por ejemplo, si solo quieres que las entradas de la categoría fotografía utilicen esta disposición, escribe “fotografía”.

Cuando haya terminado, haga clic en el botón “Guardar” y ahora esta plantilla se utilizará para todas las entradas de la categoría correspondiente.

Esta es la forma más fácil de crear múltiples plantillas de entradas personalizadas en WordPress. No requiere ningún conocimiento de código y no estropeará accidentalmente ningún archivo de tema.

Creación de plantillas de entradas únicas personalizadas por categoría mediante código

Este es otro método para aquellos que se sienten cómodos añadiendo código a los archivos de sus temas.

En primer lugar, debe añadir este código al archivo functions. php de su tema o a un plugin de fragmentos de código.

/*
* Define a constant path to our single template folder
*/
define(SINGLE_PATH, TEMPLATEPATH . '/single');
 
/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_template');
 
/**
* Single template function which will choose our template
*/
function my_single_template($single) {
global $wp_query, $post;
 
/**
* Checks for single template by category
* Check by category slug and ID
*/
foreach((array)get_the_category() as $cat) :
 
if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';
 
elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';
 
endforeach;
}

Este código primero comprueba si WordPress está solicitando una única entrada. Si es así, entonces le dice a WordPress que busque la plantilla en la carpeta /single/ de su tema de WordPress.

Ahora tienes que añadir los archivos de plantilla definidos por este código.

Conéctese a su alojamiento WordPress utilizando un cliente FTP o el Administrador de archivos en cPanel y vaya a /wp-content/themes/your-theme-folder/.

Dentro de la carpeta de tu tema actual, necesitas crear una nueva carpeta llamada ‘single’. A continuación, debe abrir esta carpeta y crear un nuevo archivo dentro de ella. Llame a este archivo single-cat-{category-slug}. Sustituya {category-slug} por el slug de su categoría.

Por ejemplo, si tiene una categoría llamada ‘Noticias’, entonces creará un archivo single-cat-news. php. Si tiene una categoría llamada ‘Consejos de viaje’, entonces creará una plantilla single-cat-travel-tips.php, y así sucesivamente.

Creating Single Post Template for Categories

Ahora, estos archivos de plantilla estarán totalmente vacíos. Como punto de partida, puedes copiar el contenido de tu archivo single.php de la carpeta de tu tema y pegarlo dentro de cada una de estas plantillas. Después de eso, tendrá que editar estas plantillas para hacer los cambios deseados.

Una vez que hayas terminado, puedes ir a tu sitio web y ver una entrada. Utilizará la plantilla que ha creado para la categoría en la que está archivada esta entrada.

Ahora supongamos que tienes una entrada archivada en dos categorías Noticias y Consejos de viaje. WordPress mostrará automáticamente la plantilla para ‘Noticias’ porque aparece primero en orden alfabético.

Por otro lado, si usted archivó una entrada en una categoría y no creó una plantilla para esa categoría, entonces WordPress volverá a la plantilla por defecto single.php de su tema.

Creación de plantillas de entradas individuales personalizadas para autores específicos

Supongamos que quieres que las entradas escritas por un autor específico tengan un aspecto diferente en tu sitio web. Puede hacerlo mediante código siguiendo la misma técnica que mostramos para las categorías.

En primer lugar, debe añadir este código al archivo functions. php de su tema o a unplugin de fragmentos de código de .

/**
* Define a constant path to our single template folder
*/
define(SINGLE_PATH, TEMPLATEPATH . '/single');
 
/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_author_template');
 
/**
* Single template function which will choose our template
*/
function my_single_author_template($single) {
global $wp_query, $post;
 
/**
* Checks for single template by author
* Check by user nicename and ID
*/
$curauth = get_userdata($wp_query->post->post_author);
 
if(file_exists(SINGLE_PATH . '/single-author-' . $curauth->user_nicename . '.php'))
return SINGLE_PATH . '/single-author-' . $curauth->user_nicename . '.php';
 
elseif(file_exists(SINGLE_PATH . '/single-author-' . $curauth->ID . '.php'))
return SINGLE_PATH . '/single-author-' . $curauth->ID . '.php';
 
}

A continuación, debe conectarse a su sitio web mediante FTP o el gestor de archivos de cPanel en cPanel y luego ir a /wp-content/themes/your-theme-folder/. Si aún no ha creado una carpeta llamada /single/ dentro de ella, entonces siga adelante y créela ahora.

Dentro de esta carpeta, debe crear una plantilla utilizando el nombre de usuario del autor en el nombre de la plantilla. Por ejemplo, single-author-johnsmith.php.

Esta plantilla estará vacía, por lo que puedes copiar y pegar el contenido de la plantilla single.php de tu tema y utilizarla como punto de partida.

Ahora puede visitar su sitio web para ver una entrada creada por un autor concreto. Utilizará la plantilla que ha creado.

Esperamos que este artículo te haya ayudado a aprender a crear plantillas personalizadas para entradas individuales en WordPress. Es posible que también desee aprender a realizar un seguimiento de los visitantes del sitio web a su sitio de WordPress, o ver nuestra lista de plugins de WordPress debe tener para hacer crecer su sitio.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Descargo: Nuestro contenido está apoyado por los lectores. Esto significa que si hace clic en algunos de nuestros enlaces, podemos ganar una comisión. Vea cómo se financia WPBeginner , por qué es importante, y cómo puede apoyarnos. Aquí está nuestro proceso editorial .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

El último kit de herramientas de WordPress

Obtenga acceso GRATUITO a nuestro kit de herramientas - una colección de productos y recursos relacionados con WordPress que todo profesional debería tener!

Reader Interactions

70 comentariosDeja una respuesta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Jasmine says

    I am getting this message when I try to use the code:

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘my_single_template’ not found or invalid function name.

    Any ideas as to why?

  3. Iulian says

    All good but it breaks the default single.php.

    In other words this “On the other hand, if you filed a post in a category and didn’t create a template for that category, then WordPress will fallback to the default single.php template of your theme.” is not working.

    Any solution?

  4. Thomas says

    Hi, I am trying to follow the step:
    Open the single.php file and then copy everything after the get_header() line.
    Under:
    Manually Creating Custom Single Post Templates in WordPress
    However, I don’t have any “get_header()” function in that file.

    • WPBeginner Support says

      Your specific theme may have some unique coding, we would recommend reaching out to the support for your specific theme and they should be able to assist.

      Administrador

  5. bob says

    Thanks for this. All my auto generated files (author, not found etc) are using my site template then putting a white section with white text on thepage. its also starting at the top of the page (so its white text on a white background mostly hidden behind a page header)

    I believe your article will help me sort this mess out.

    Thank you

    • WPBeginner Support says

      Our article should help and if you reach out to your theme’s support they may be able to assist as well :)

      Administrador

  6. John says

    Am I correct in thinking that once you create a custom post template php file, for it to work as a template, you still need to code the php file, as there is no way to save a new post as a template. Is this correct?

    Thank you for your help.

    • WPBeginner Support says

      That is correct, for changing the template unless you are using a page builder there is not a method to set it up without coding.

      Administrador

  7. Haripal Reddy says

    Hello Author,

    I followed the steps as you mentioned. I have CPT albums. single-albums.php copied same code to other file wpb-single-albums.php and added template code like /*
    * Template Name: custom template
    * Template Post Type: albums
    */
    and changed some required changes. But after selecting this template in edit post but it displays default one (single-albums.php) page.

    How can i fix this please help

    • WPBeginner Support says

      You may want to check the current working template to ensure you have the post type correct

      Administrador

  8. Alice says

    Thanks for your great post. I have 2 questions: Are single post templates the same with custom post type templates? If the are different, can you show me how to create a custom post type template?

  9. aziz says

    hello
    than you for the post
    i did everything and worked like i wanted.
    but i had a small problem
    after adding the code to function.php single.php stopped showing data
    is there anything i can do?

  10. Binesh says

    Hi, Thanks for your Tutorial…

    As per your tutorial I have created a custom Post type. But now I am facing an issue with comment. While submitting the comment it redirected to search…
    Pls suggest a solution for this..
    Thanks in Advance

  11. Mike says

    Hello.

    I’m using this & enjoying it greatly! :)
    However, I’m finding the following warning in my error logs around this code:

    [warn] mod_fcgid: stderr: PHP Warning: Use of undefined constant SINGLE_PATH – assumed ‘SINGLE_PATH’ (this will throw an Error in a future version of PHP)

    Any thoughts on how to fix that?

    Your snippet starts with “define(SINGLE_PATH,…” so I’m not sure what else to do here.

    • WPBeginner Support says

      That error is saying it wants SINGLE_PATH to be surrounded by single quotes (”) which you can do for that warning :)

      Administrador

  12. Jojo says

    So I followed your steps and its working for the new category slug single page but not for the default single.php.

    How can I get this to work? Perhaps the default single.php path is wrong?

    Thanks!

  13. Hil says

    Hi,

    I am overthinking this but…if I want every blog post to look the same, do I just create the Layout (I use Divi theme), use the above first method (make a new version of single.php named properly) and choose that every time I want to create a post? That simple?

    Also, to add the custom CSS, do you add to the php file, and how? Where within it do you add it? How should it look? That’s the part that I haven’t yet found any reference on how to do. Can you do an example based on just having every blog post look one way?

    Thank

  14. Malgorzata says

    Hi, thanks dfor great tutoriasl. It is working amazing but not for new categories, which doesnt have special template. Unfortunatley it is not getting the code from default single.php file. I will appreciate some help how to make it work.

  15. STEVE says

    Hi, Thanks for the tutorial!

    I have a question. How would we apply custom CSS that would only effect the Posts pages?

    Thanks

  16. TRAVIS says

    What if you want to make your new template the default for everything. So that anytime a post is created it is automatically selected as the default template?

  17. Jae says

    I bet there are plugins that you can use to do the job without the hassle of coding and child themes. It would’ve been great if you’d researched and shared that in this post too.

  18. peyman says

    I use your method but I can’t set custom css for this posts.
    for example in function.php when I check is_page_template(‘single-cat-news’) the statement not getting true and my custom css for this kind of post not running. what should I do in this case?

    • Bikram says

      True.
      I’m also having this problem. The full-width template works well for post and pages but when it comes to custom post type, the CSS codes don’t work and goes back to normal page size without a sidebar.
      I’m having a hard time finding a solution to that problem.

  19. Mike says

    Need some additional help with this…

    Following the instructions on this page (along with the small modifications noted within my comments on 12/2/17 and 12/12/17), I’ve been able to get this working reliably.

    HOWEVER, I’ve run into the issue where using this method to call a custom template does not seem to get registered with the call of body_class classes.

    For example, if I set a custom template on a page (where I’m using WordPress’ “Template” drop-down within the “Page Attributes” sidebar in the editing view – then the body_classes that are output would include that template name.

    Such as:

    <body class="page-template-my_custom_template page page-id-2..."

    But, using this method, the body classes just return:

    <body class="page-template-default page page-id-2..."

    Any idea on how to ensure the body classes reflect a custom single post template?

    • Mike says

      Here’s the answer (for my theme, at least – your experience may vary).

      Adding the following to [b]functions.php[/b] did the trick for me:

      add_filter('body_class','add_category_to_single');
        function add_category_to_single($classes) {
          if (is_single() ) {
            global $post;
            foreach((get_the_category($post->ID)) as $category) {
              // add category slug to the $classes array, starting with 'category-'...
              $classes[] = "category-$category->category_nicename";
            }
          }
          // return the $classes array
          return $classes;
        }
      
  20. Dzungx Corn says

    I created a single-cat-news.php file for “News”. My “News” category has two child: “Camera” and “Smartphone”. The post in “Smartphone” display in single-cat-news.php (S after N in alphabet), but the post in “Camera” display in default single.php (C before N in alphabet). I want post in “Camera” display in single-cat-news.php, what must I do? I selected both “News” and “Camera” for my post.

  21. Sarmad Gardezi says

    Im viewing your Blog from last 2 years. I explored whole web to find this but i got the correct working code from here i just love your Blog keep it up :)

  22. Mike says

    When using this approach to specify a custom post template for a single post within a specific category, I was finding that WordPress was NOT defaulting back to single.php in instances where a single-cat-WHATEVER.php file didn’t exist for a specific category.

    I fixed this by adding the following line before the end of the function:

    else
    return SINGLE_PATH . '/single.php';

    So that, this code:


    /**
    * Checks for single template by category
    * Check by category slug and ID
    */
    foreach((array)get_the_category() as $cat) :

    if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

    elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';

    endforeach;
    }

    Became this:


    /**
    * Checks for single template by category
    * Check by category slug and ID
    */
    foreach((array)get_the_category() as $cat) :

    if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

    elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';

    else
    return SINGLE_PATH . '/single.php';

    endforeach;
    }

    Does this seem like the right approach? Or, is there something else that I may have done to break the default functionality?

  23. Mike says

    Thank you for this clear ‘how to.’

    One note: for those of us using a CHILD THEME, I’ve found that changing…

    define(SINGLE_PATH, TEMPLATEPATH . ‘/single’);

    to:

    define(SINGLE_PATH, get_stylesheet_directory() . ‘/single’);

    (within the “Define a constant path to our single template folder” section) ensures that child theme’s directory is checked for single templates instead of the parent theme’s directory.

    This may also be the reason that it’s not working for some of the other commenters above.

    Good luck, everyone!

    • Stephanie Lewis says

      Thank you so much for your help! I was wondering why it kept pointing me back to the parent theme instead of the child theme.

  24. Olayinka says

    Thank you for this article.
    I will want to know how I can further customise the layout of this single custom post template, like placing an image in the post before the content and in the footer.

  25. oussama says

    Hi,
    I need to change the order of 3 things in the post page which they are in the bottom of the article:
    1-a pagination plugin.
    2-an ad.
    3-social share icons.

    I want to make them in the following order (vertically):
    1-the ad
    2-the social share icons
    3-the pagination plugin

    How can I do that please?

  26. Linda Holiner says

    Thank you for your great tutorials. I am having trouble with this one. I added the code to my functions.php but I’m not getting the single post template. Do I need to make a call to the function or does WordPress do that? Is there some way I can debug the function?

    I just want posts of a particular category to display differently when you link to them.

  27. Taufiq Mahmud says

    I wanted to make a custom post page where registered user of my site can able to post without using wordpress’s default post.php

  28. Pierrick says

    Hi! Thank you for this tutorial, but I’m quite new to web design and I started creating a whole wordpress theme. Everything works fine on my website, but I am trying to make it possible to add pages that all use a template I created, (like the page of a product in a catalogue) but I have no idea how to do that. I first tried to do so by creating a page template in which I put loops that display the content of an article or a page, such as its title, its text and the values of some custom fields. To do so I used a query_posts, but it requires to put the post’s or page’s id with “page_id=” or “p=”, which means the template is for one specific page, and I would have to create a template for each new page I add to this catalogue , and precising the id of the page/post manually in it, while what I wanted was to create a single template for all the pages of the catalogue…
    So while doing my research to find a solution, I found your article, and I tried to create a post using the new single post template, but no matter which template I select in the list, when I go to the url of the post it displays my home page… I’m probably doing everything wrong, and I’m not even sure I understood what a single post is and if it’s really what I need… I would really appreciate it if you could give me some clues on what I should do to solve my problem, or if there’s some tutorial somewhere that could help me…
    Thank you,

    Pierrick.

    • WPBeginner Support says

      Hi Pierrick,

      We are not sure we understand your problem completely. However, if you just want to create a template to be used by any page then custom page template is the right approach. Since you want users to be able to see any page, this means you don’t need to use query_posts, your loop will begin with the standard

      <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
      //
      		// Post Content here
      		//
      	} // end while
      } // end if
      ?>
      

      Administrador

  29. alex says

    Hi,

    I have a local setup with WP 3.7.x and Template Post Type: post, page, product is not available.

    How can i create seperate caterory php files for each post category???

    single-{slug}.php
    category-{slug}.php

    all doesn’t seem to work

    Any tips?

  30. Mark says

    I have set this up to work with categories, however when I select a post that does not have a category it fails to pick up the default template and does not display the post. I suspect my theme may be at fault. How would I hard code the single.php in the parent directory as the default to use if no category template exists ?

    Works perfectly if I copy the single.php into the /single/single-cat-name.php file but I don’t want 40+ duplicate files.

    • Eric Besso says

      first copy single.php to the /single folder

      then include this code right before the endforeach;

      else

      return SINGLE_PATH . ‘/single.php’;

  31. Lyssie says

    This is exactly what I was looking for, thank you for spelling this out so simply! It leaves me with a question though: I removed my sidebar but now there’s just an empty space where it used to be. How can I stretch the main content section to cover the entire space? Thanks again!

    • WPBeginner Support says

      Hi Lyssie,

      That’s because your theme has defined content area width relative to the sidebar. You need to use inspect tool to find out which CSS class your conntent-area uses and then adjust by adding custom CSS to make it full width.

      .page-template-full-width .content-area {
          width: 100%;
          margin: 0px;
          border: 0px;
          padding: 0px;
      }
      
      .page-template-full-width .site {
      margin:0px;
      }
      

      Please see our guide on how to create full width page in wordpress

      Administrador

      • Lyssie says

        Thanks for the fast response! This was very helpful! Now, if I see:
        div id=”primary” class=”content-area”>

        when I use the inspect tool, which is the class my content area uses?

        • Lyssie says

          Oops, that didn’t come out right.
          div id=”primary” class=”content-area”
          main id=”main” class=”site-main” role=”main”

          article id=”post-4773″ class=”post-4773 post type-post status-draft format-standard hentry category-travel-2″
          div id=”featured-image”
          /div

  32. Joe Yee says

    That’s a great article and should helps a no-coder person like me. Customization of template would be something scary that you might break the theme altogether. Do you recommend make the custom template on a child theme or is it okay to do it right on the theme. Thanks a bunch.

    • WPBeginner Support says

      Hi Joe,

      You will not be changing any of your theme’s existing files. Instead, you will be creating a new file. If anything goes wrong you can simply delete the template and your site will be back to normal.

      Yes creating a child theme is the recommended best practice.

      Administrador

Deja tu comentario

Gracias por elegir dejar un comentario. Tenga en cuenta que todos los comentarios son moderados de acuerdo con nuestros política de comentarios, y su dirección de correo electrónico NO será publicada. Por favor, NO utilice palabras clave en el campo de nombre. Tengamos una conversación personal y significativa.