Seguro que estás harto de oír hablar de los temas hijos y nunca nadie te ha contado como usarlos. Un problema que hemos tenido todos en algún momento, ya que se ha centrado durante mucho tiempo todo el esfuerzo en el desarrollo y existe todavía muy poca documentación al respecto.
Hoy vamos a intentar aprender a utilizar un tema hijo. ¿Te apuntas?You must be bored of reading about child themes, but maybe no one has told you how to use them. We all have had this problem because we have been focused all this time in development, and there’s little documentation about it yet.
Today we are going to learn how to use a child theme. Interested?
¿Qué es un tema hijo?
Como hemos contado en alguna otra ocasión, es un tema que hereda funciones de un tema padre. Es decir, lee toda la información de un tema existente y modifica ciertas acciones.
¿Por qué usamos temas hijos?
Es sobre todo un tema funcional. Utilizar un tema hijo facilita mucho el trabajo porque hace más simples las actualizaciones. Para entenderlo, vamos a poner un ejemplo.
Imaginemos que tenemos el nuevo tema por defecto de WordPress, Twenty Ten, y queremos hacer modificaciones. Twenty Ten es un tema vivo, es decir, que se actualiza cada vez que actualizamos nuestro WordPress, lo que tiene ventajas e inconvenientes. La ventaja principal es que, al ser un tema vivo, está siempre actualizado con los últimos cambios que se hayan realizado en el core (el núcleo de WordPress). La desventaja, que cualquier cambio que hayamos realizado sobre él se perderá en la actualización.
El tema hijo nos resultará útil como un contenedor para nuestros cambios separado del tema principal, de forma que cuando éste se actualice no perdamos nuestros cambios.
No es necesario que padre e hijo se parezcan ;). El tema hijo puede construirse a partir de cualquier tema ya existente. Una vez hecho, tenemos la seguridad de que será compatible con todas las futuras versiones de WordPress. Empresas como la nuestra son capaces de hacerlo sin mucha dificultad. (Consúltanos si estás interesado).
¿Cómo se utiliza un tema hijo?
Crear un tema hijo es más sencillo de lo que parece. Sólo hay que:
- Crear un directorio nuevo en la carpeta wp-content/themes.
- Crear dentro de él un archivo style.css.
- En el style.css, indicar que es un tema hijo y quién es su padre.
Con esto ya tenemos nuestro tema hijo. Fácil, ¿eh? Vamos a seguir los pasos y a hacer unas pequeñas modificaciones para ver su efecto. Lo primero es indicar que el tema es hijo de su padre.
/*
Theme Name: Tema hijo
Theme URI: http://temahijo.com/
Description: Tema hijo de Twenty Ten para WordPress
Author: Mecus
Author URI: https://mecus.es/
Template: twentyten
Version: 0.1.0
*/
Nótese que template tiene que coincidir con el nombre del directorio del tema padre.
Con este código todo lo que escribamos en el style.css sustituirá a lo indicado en el tema padre.
Probando el tema hijo
Para probar que el tema hijo funciona lo más fácil es cambiar algún color, para ver de forma visual qué está ocurriendo. Lo primero que tendremos que hacer es añadir la plantilla del tema padre. Para eso utilizaremos el siguiente código:
@import url('../twentyten/style.css');
Y ahora escribiremos las directivas que queramos modificar. Hay que tener en cuenta aquí, de nuevo, que cualquier cambio sustituirá a las líneas que haya escritas en el tema padre. En nuestro ejemplo modificaremos cómo se muestran los asides (artículos cortos) en Twenty Ten.
Extendiendo el tema hijo
Como hemos visto, un tema hijo necesita únicamente un archivo style.css para funcionar, pero puede utilizar más archivos. El que nos será más útil, sin duda será el functions.php.
El archivo functions.php, a diferencia del archivo style.css, añade funcionalidades al functions.php existente. El sistema utilizará el functions.php de forma automática, por lo que únicamente tendremos que añadir nuestras funciones al archivo.
Sin duda la función más interesante para añadir en nuestro archivo functions.php es el reconocimiento del favicon, del que carece el tema padre.
Para eso, crearemos nuestro archivo functions.php y añadiremos el siguiente código:
<?php
function favicon_link() {
$favicon = get_bloginfo('template_url').'/images/favicon.ico';
echo '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'" />' . "\n";
}
add_action('wp_head', 'favicon_link');
?>
En nuestro caso hemos alojado el favicon en el directorio /images/ del tema, por lo que lo buscaremos ahí.
Extendiendo (aún más) el tema hijo
¿Eres de los que quieres control total? ¡Estupendo! Sólo tienes que crearte tus propias páginas en el directorio de tu tema hijo y éstas sustituirán a las páginas originales del tema padre. Puedes modificar hasta el index.php y crear páginas que no existan en el tema padre (como tag.php para las etiquetas, caso de que no existiera).
Ya tienes las claves. Ahora toca experimentar 🙂
Para desarrolladores
Recordad el uso de add_action y add_filter en vuestros temas hijos. Twenty Ten tiene 150 filtros y 60 acciones, así que ¡úsalas!
** Información extraída del archivo Child Themes del Codex de WordPress – Autor: Demetris.
What is a Child Theme?
As we have told some times before, a child theme is a theme that inherits functions of a parent theme. It reads all the information about an existing theme and modifies some actions.
Why we use Child Themes?
Because it’s very useful. Using a child theme makes our work easier. To understand it better, let’s see an example.
Suppose that we have the new default WordPress theme, Twenty Ten, and we want to make some modifications. Twenty Ten is an alive theme. It means that every time we update our WordPress the theme is updated too. It has advantages and disadvantages. The main advantage is that being a live theme it’s always updated with the last changes done in the core. The disadvantage is that every change we have done is lost in the update.
The child theme will be useful as a container for our changes being separated of the parent theme, so if it updates we will not lost our changes.
Parent and child do not necessary look alike ;). Child theme may be built from any already built. Once it’s properly built, we can be sure our theme will be compatible with all upcoming versions of WordPress. Companies like us can do it for you. Please, contact us if you have any question.
How we use a Child Theme?
Creating a child theme is very easy. Just follow:
- Create a new directory in wp-content/themes.
- Create the file style.css inside it.
- In style.css you must indicate that it’s a child theme and who is his father.
Doing this we have our child theme. Easy, huh? Now let’s change some little things to see how it works. The first we must do is indicate that the child theme is the child of his father ;).
/*
Theme Name: Child theme
Theme URI: http://childtheme.com/
Description: Twenty Ten Child Theme for WordPress
Author: Mecus
Author URI: https://mecus.es/
Template: twentyten
Version: 0.1.0
*/
Here, in the header of the style.css file, template must coincide with the name of the directory of the parent theme. Using this code, everything that we write in style.css will replace and override all the things written in the parent style.css.
Testing the Child Theme
To test the child theme changing some colors is the easiest, seeing directly what is happening. First of all, we have to add the parent stylesheet. To do this, we will use this code:
@import url('../twentyten/style.css');
And now we will write all the things that we want to change. We must have in mind that any change will override what is written in the parent theme. In our example we are modifying the asides in Twenty Ten.
Extending the child theme
As we have seen, a child theme only needs a style.css file to work, but we can use more files. The most useful file that we can use here is, without doubt, functions.php.
functions.php file, unlike style.css, adds functionality to the existing functions.php parent file. The system will use the child functions.php automatically, so we only have to add our functions to it.
One of the most interesting things to add to our functions.php is the favicon, who is not in the parent theme. To do this, we will create our functions.php file and will add this code:
<?php
function favicon_link() {
$favicon = get_bloginfo('template_url').'/images/favicon.ico';
echo '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'" />' . "\n";
}
add_action('wp_head', 'favicon_link');
?>
In our example we have saved our favicon in the theme /images/ directory.
Extending (more) the child theme
Do you want total control? Great! You only need to create your own pages in the directory of your child theme and they will override the originals in the parent theme. You can modify even index.php file and create nonexistent pages in the parent theme (like tag.php for tags in the themes in which it’s absent).
Now you have the clues. Let’s experiment 🙂
Developers info
Remember the use of add_action and add_filter in your child themes. Twenty Ten has 150 filters and 60 actions, so use them!
** Data from Child Themes – WordPress Codex – Author: Demetris.
16 respuestas a «Creando temas hijos // Making child themes»
No consigo que me salga el favicon… He sustituido «template_url» en functions.php por mi url y he metido el favicon.ico dentro de la carpeta /images (supongo que la carpeta /images del tema padre? o del tema hijo? de cualquiera de las dos formas no me aparece… ¿Puede ser por algo de permisos?
Ya me ha salido! Qué tonta! había sustituido «template_url» por mi url pero no había que hacer eso! jeje.
[…] Lo descubrí trabajando con mis grandísimos amigos de Mecus. En una de las entradas de su web, explican a la perfección el funcionamiento y las tremendas ventajas de trabajar de esta manera cuando diseñamos para […]
Como tutorial introductorio genial! He seguido vuestros pasos y ya tengo un tema hijo sobre el que experimentar, a veces cuesta encontrar tutoriales en castellano sobre estos temas. Hasta me ha servido el comentario de Lidia sobre el favicon porque me pasaba lo mismo… ^^
Excelente información por más que buscaba no había dado con ella, ahora solo queda experimentar como has dicho, saludos!
Creo que lo del favicon ya no funciona. Hace algún tiempo lo conseguí, pero ahora estoy haciéndolo y no me funciona. La ruta de las imágenes en la que busca es la del tema padre. A mí me ha funcionando de la siguiente forma:
function childtheme_favicon() { ?>
<link rel="shortcut icon" href="/images/favicon.ico»>
<?php }
add_action('wp_head', 'childtheme_favicon');
Ha cambiado algo o estoy haciendo yo algo mal? Como os digo, hace tiempo recuerdo que sí me funcionó…
Buenas. El problema aquí es que estás utilizando una ruta incompleta.
Tienes que utilizar:
<link rel="shortcut icon" href="<?php bloginfo(‘stylesheet_directory’); ?>/images/favicon.ico»>
Sí, me di cuenta. Sustituí lo que ponéis de:
$favicon = get_bloginfo(‘template_url’).’/images/favicon.ico’;
por:
$favicon = get_bloginfo(‘stylesheet_directory’).’/images/favicon.ico’;
Lo que me extraña es que hace tiempo sí que me funcionó así, supongo que metería el favicon en la carpeta images del twentyten en vez de en el tema hijo!
Ya voy entendiendo bien cómo se hace! Gracias!
La cosa es que antes se podían utilizar indistintamente, y desde 3.0 hay que utilizar stylesheet_directory, que además sería el más correcto.
Me apunto actualizar el artículo.
Un saludo 🙂
Tengo problemas al crear temas hijo. Una vez hechos todos los pasos del tutorial, en la sección de gestión de temas de WP no sale el tema hijo. En su lugar tengo una nota que me comenta:
Temes estropeados:
Los temas siguientes estan instalados pero estan incompletos. Los temas deben tener, como mínimo, una hoja de estilos y una plantilla.
El tema padre no existe.
Alguien sabria decirme la razón de este error i como proceder para solucionarlo?
Muchas gracias
lluc
Buenas. Pásate por los foros de WordPress en Español y te ayudamos ahí 😉
http://es.forums.wordpress.org
[…] que es complicado modificarlo? Es mucho más sencillo de lo que crees. Puedes ver los pasos a dar para crear temas hijos en este tutorial y una guía para cambiar la […]
[…] Creando temas hijos. […]
Tengo una pequeña duda con los temas hijos… Si yo meto la carpeta de twenty eleven de images en mi tema hijo ¿no coge por defecto esas imágenes? Tendría que cambiar todas las rutas de las imágenes? Hay alguna forma de hacer esto en functions.php? para que coja las imágenes de mi tema hijo?
Yo lo he conseguido colocando las imagenes personalizadas en una carpeta «images» dentro del directorio del tema hijo.
Y después, añadiendo la ruta de cada una de esas imágenes al «style.css» del tema hijo. He tenido que hacerlo así aunque escriba exactamente la misma ruta que en el tema padre. Si no incluía la ruta, al tomar esa línea del «style.css» del tema padre, se iba a buscar la imagen a la carpeta «images» del tema padre.
Ejemplo:
background: url(‘images/arrow.gif’) no-repeat 0 2px; /* añadido para que lo encuentre en el tema hijo */
[…] Creando child themes para WordPress […]