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 un tema hijo de WordPress (guía para principiantes)

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.

¿Quieres crear un tema hijo en WordPress?

Un tema hijo es un tema de WordPress que hereda la funcionalidad de otro tema de WordPress. Muchos usuarios crean un tema hijo para su tema actual para poder personalizar con seguridad el diseño de su sitio web sin perder los cambios cuando el desarrollador del tema publica una actualización.

En este artículo, le mostraremos cómo crear un tema hijo para su sitio de WordPress.

How to Create a WordPress Child Theme

¿Cómo funciona un tema hijo y por qué es necesario?

Un tema hijo hereda todas las características, funciones y estilos de otro tema de WordPress. Cuando se crea un tema hijo, el tema original se denomina tema padre.

La herencia incluye el archivo style.css del tema padre, que define el estilo principal del tema. El tema hijo puede anular o ampliar las propiedades heredadas añadiendo sus propios archivos o modificando los existentes.

Aunque es posible personalizar su tema de WordPress sin instalar un tema hijo, hay varias razones por las que puede necesitar uno de todos modos:

  • Los temas hijo protegen sus personalizaciones durante las actualizaciones del tema, evitando que se sobrescriban. Si modificas el tema padre directamente, esos retoques pueden desaparecer al actualizar.
  • Los temas hijo permiten probar con seguridad nuevos diseños o características sin alterar el tema original del sitio, de forma similar a un entorno de pruebas.
  • Si sabes programar, los temas hijo pueden hacer que el proceso de desarrollo sea más eficaz. Los archivos de un tema hijo son mucho más sencillos que los de un tema padre. Puedes centrarte en modificar solo las partes del tema padre que quieras cambiar o ampliar.

Qué hacer antes de crear un tema hijo de WordPress

Hemos visto a muchos usuarios de WordPress entusiasmados por sumergirse en la parte técnica, solo para desanimarse cuando aparecen errores. Lo entendemos. Por eso es importante saber en qué te estás metiendo antes de crear un tema hijo.

Te recomendamos que hagas algunas cosas antes de continuar con esta guía paso a paso:

  1. Tenga en cuenta que trabajará con código. Como mínimo, necesitarás conocimientos básicos de HTML, CSS, PHP y, opcionalmente, JavaScript para entender qué cambios necesitas hacer. Puedes leer más acerca de esto en el manual de temas de WordPress.
  2. Elija un tema principal que tenga el diseño y las características que desea para su sitio web. Si es posible, busca uno en el que solo tengas que hacer unos pocos cambios.
  3. Utilice un sitio regional o un sitio de ensayo para el desarrollo del tema. Usted no quiere crear errores involuntarios en su sitio en vivo.
  4. Haga primero una copia de seguridad desu sitio web.

Hay varias formas de crear un tema hijo a partir de un tema existente. Uno es con código manual, mientras que otros requieren un plugin, que es mucho más fácil para los principiantes.

El primer método puede parecer intimidante si careces de experiencia técnica. Dicho esto, aunque elijas uno de los métodos de plugin, te recomendamos que leas el método manual para familiarizarte con el proceso y los archivos implicados.

Consejo profesional: ¿Quieres personalizar tu tema sin crear un tema hijo? Utilice WPCode para activar de forma segura nuevas características con fragmentos de código personalizados sin romper su sitio web.

Con todo esto en mente, vamos a ver cómo crear un tema hijo en WordPress. Puedes saltar al método que prefieras enlazando a continuación:

Método 1: Crear un tema hijo de WordPress manualmente

En primer lugar, debe abrir /wp-content/themes/ en la carpeta de instalación de WordPress.

Puedes hacerlo utilizando el gestor de archivos de tu alojamiento WordPress o un cliente FTP. La primera opción nos parece mucho más sencilla, así que la utilizaremos.

Si es cliente de Bluehost, acceda al tablero de su cuenta de alojamiento y vaya a la pestaña “Sitios web”. A continuación, haga clic en “Ajustes”.

Bluehost site settings

En la pestaña “Visión general”, desplácese hasta la sección “Enlaces rápidos”.

A continuación, selecciona “Gestión de archivos”.

Bluehost File Manager button

En esta fase, debe ir a la carpeta public_html de su sitio web y abrir la ruta /wp-content/themes/.

Aquí, basta con hacer clic en el botón “+ Carpeta” en la esquina superior izquierda para crear una nueva carpeta para su tema hijo.

Creating a new folder in Bluehost file manager

Puedes ponerle el nombre que quieras a la carpeta.

Para este tutorial, sólo usaremos el nombre de carpeta twentytwentyone-child ya que usaremos Twenty Twenty-One como nuestro tema padre. Una vez hecho esto, haz clic en “Crear nueva carpeta”.

Naming a new child theme file in Bluehost file manager

A continuación, debe abrir la carpeta que acaba de crear y hacer clic en “+ Archivo” para crear el primer archivo para su tema hijo.

Si utiliza un cliente FTP, puede utilizar un editor de texto como el Bloc de notas y subir el archivo más tarde.

Creating a new file in Bluehost file manager

Siga adelante y nombre este archivo ‘style.css’, ya que es la hoja de estilos principal de su hijo y contendrá información acerca del tema hijo.

A continuación, haga clic en “Crear nuevo archivo”.

Creating a new stylesheet file in Bluehost file manager

Ahora, basta con hacer clic con el botón derecho del ratón en el archivo style.css.

A continuación, haga clic en “Editar” para abrir una nueva pestaña, como en la captura de pantalla siguiente.

Editing a style.css file in Bluehost file manager

En esta nueva pestaña, puedes pegar el siguiente texto y ajustarlo según tus necesidades:

/*
Theme Name:   Twenty Twenty-One Child
Theme URI:    https://wordpress.org/themes/twentytwentyone/
Description:  Twenty Twenty-One child theme
Author:       WordPress.org
Author URI:   https://wordpress.org/
Template:     twentytwentyone
Version:      1.0.0
Text Domain:  twentytwentyonechild
*/

Una vez hecho esto, sólo tienes que hacer clic en “Guardar cambios”.

Saving a stylesheet file in Bluehost file manager

Lo siguiente que tienes que hacer es crear un segundo archivo y llamarlo functions.php. Este archivo importará o pondrá en cola las hojas de estilos de los archivos del tema padre.

Una vez creado el documento, añade el siguiente código wp_enqueue:

add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
    $parenthandle = 'twenty-twenty-one-style'; // This is 'twenty-twenty-one-style' for the Twenty Twenty-one theme.
    $theme = wp_get_theme();
    wp_enqueue_style( $parenthandle, get_template_directory_uri() . '/style.css', 
        array(), // if the parent theme code has a dependency, copy it to here
        $theme->parent()->get('Version')
    );
    wp_enqueue_style( 'custom-style', get_stylesheet_uri(),
        array( $parenthandle ),
        $theme->get('Version') // this only works if you have Version in the style header
    );
}

Una vez hecho esto, sólo tienes que guardar el archivo como en el paso anterior.

Nota: Para este método, le recomendamos que lea la documentación oficial de Child Themes and Including Assets para asegurarse de que las hojas de estilos de su tema hijo se cargan correctamente.

Ya has creado un tema hijo muy básico. Cuando vayas a Apariencia ” Temas en tu panel de administrador de WordPress, deberías ver la opción Twenty Twenty-One Child.

Haga clic en el botón “Activar” para empezar a utilizar el tema hijo en su sitio.

Activating a child theme in WordPress admin

Método 2: Crear un tema hijo clásico con un plugin

El siguiente método utiliza el plugin Child Theme Configurator. Este plugin de WordPress fácil de usar te permite crear y personalizar temas hijo de WordPress rápidamente sin usar código, pero solo funciona bien con un tema clásico (sin bloques).

Lo primero que debe hacer es instalar y activar el plugin de WordPress. Una vez activado, debe ir a Herramientas ” Temas Hijo en su escritorio de WordPress.

En la pestaña Padre/Hijo, se le pedirá que elija una acción. Selecciona “CREAR un nuevo tema hijo” para empezar.

Creating a new child theme with Child Theme Configurator

A continuación, seleccione un tema principal en el menú desplegable. Seleccionaremos el tema Hestia.

A continuación, sólo tiene que hacer clic en el botón “Analizar” para asegurarse de que el tema es adecuado para utilizarlo como tema principal.

Choosing a parent theme in Child Theme Configurator

A continuación, se le pedirá que indique el nombre de la carpeta en la que se guardará el tema hijo. Puede utilizar cualquier nombre de carpeta que desee.

A continuación, debe seleccionar dónde guardar los nuevos estilos: en la hoja de estilos principal o en una separada.

La hoja de estilos principal es la hoja de estilos por defecto que viene con su tema hijo. Cuando guardas nuevos estilos personalizados en este archivo, estás modificando directamente los estilos principales de tu tema hijo. Cada modificación sobrescribirá el estilo del tema original.

La opción separada le permite guardar un nuevo estilo personalizado en un archivo de hoja de estilos separado. Esto es útil si desea conservar el estilo del tema original y no sobrescribirlo.

Para fines de demostración, elegiremos la primera opción. Pero a medida que se vuelve más creativo con las personalizaciones de su tema hijo, siempre puede repetir este proceso y seleccionar la segunda opción.

Choosing where to save the stylesheet in Child Theme Configurator

A continuación, debe elegir cómo se accederá a la hoja de estilos del tema principal.

Usaremos por defecto ‘Usar la cola de estilo de WordPress’ ya que permitirá al plugin determinar las acciones apropiadas automáticamente.

Choosing the parent theme stylesheet handling in Child Theme Configurator

Cuando llegue al paso 7, deberá hacer clic en el botón “Haga clic para editar los atributos del tema hijo”.

A continuación, puede rellenar los datos de su tema hijo.

Filling out the child theme details in Child Theme Configurator

Al crear un tema hijo manualmente, perderá los menús y widgets del tema padre. Child Theme Configurator puede copiarlos del tema padre al tema hijo. Marque la casilla en el paso 8 si desea hacerlo.

Por último, haga clic en el botón “Crear nuevo tema hijo” para crear su nuevo tema hijo.

Clicking the Create New Child Theme button in Child Theme Configurator

El plugin creará una carpeta para tu tema hijo y añadirá los archivos style.css y functions.php que utilizarás para personalizar el tema más adelante.

Antes de activar el tema, debes hacer clic en el enlace situado cerca de la parte superior de la pantalla para obtener una vista previa y asegurarte de que se ve bien y no rompe tu sitio.

Previewing a child theme in Child Theme Configurator

Si todo parece funcionar, haga clic en el botón “Activar y publicar”.

Ahora, su tema hijo se activará.

En esta fase, el tema hijo tendrá el mismo aspecto y se comportará exactamente igual que el tema padre.

Activating a child theme after it was made with Child Theme Configurator

Método 3: Crear un tema hijo en bloque con un plugin

Si utilizas un tema de bloque, WordPress te ofrece una forma sencilla de crear un tema hijo con el plugin Create Block Theme.

En primer lugar, tendrá que instalar y activar el plugin de WordPress. Después de eso, vaya a Apariencia ” Crear tema de bloque.

Aquí, simplemente seleccione ‘Crear hijo de [nombre del tema]’. En este ejemplo utilizaremos Twenty Twenty-Four.

Una vez que hayas seleccionado esa opción, rellena la información de tu tema.

Creating a child theme with Create Block Theme

Debajo de eso, puedes hacer más cosas como subir una captura de pantalla del tema para diferenciarlo de otros temas, enlazar a plugins imprescindibles de WordPress, añadir etiquetas de tema, etc.

Cuando haya terminado de configurar los ajustes, desplácese hacia abajo y pulse el botón “Generar”.

Generating a child theme with Create Block Theme

El plugin creará y descargará un nuevo archivo zip del tema hijo en su ordenador.

Si lo abres, verás tres archivos: readme, style.css y theme.json.

El archivo theme.json define varios aspectos de un tema de bloque, incluyendo sus colores, tipografía, disposición y más. El plugin crea este archivo por defecto para que puedas anular o ampliar el estilo del tema padre en el tema hijo más adelante.

En este punto, todo lo que tienes que hacer a continuación es ir a Apariencia ” Temas.

A continuación, haz clic en “Añadir nuevo tema”.

Adding a new theme in WordPress

A continuación, seleccione “Subir tema”.

A continuación, seleccione el archivo zip y haga clic en “Instalar ahora” para instalar el tema de WordPress.

Uploading a child theme in WordPress

Consejo adicional: Averigüe si su tema tiene un generador de temas hijo

Si tiene suerte, es posible que su tema de WordPress ya disponga de una característica para crear un tema hijo.

Por ejemplo, si utilizas Astra, puedes ir al sitio web del generador de temas hijo de Astra. Después de eso, sólo tienes que rellenar el nombre de tu tema hijo y hacer clic en el botón ‘Generar’.

Astra Child Theme Generator website

A continuación, su navegador descargará automáticamente el tema hijo en su ordenador, que podrá instalar usted mismo en WordPress.

También hemos encontrado otros temas populares de WordPress que tienen un generador de temas hijo:

Cómo personalizar su tema infantil clásico

Nota: Esta sección es para usuarios de temas clásicos de WordPress. Si utilizas un tema de bloques, omite la sección siguiente.

Técnicamente, puede personalizar su tema hijo sin código utilizando el Personalizador de temas. Los cambios que realice no afectarán al tema principal. Si aún no se siente cómodo con el código, entonces no dude en utilizar el Personalizador.

Dicho esto, también recomendamos personalizar el tema hijo con código.

Además de aprender más sobre el desarrollo de temas de WordPress, la personalización del código permite documentar los cambios en los archivos del tema hijo, lo que facilita su seguimiento.

Ahora, la forma más básica de personalizar un tema hijo es añadiendo CSS personalizado al archivo style.css. Para ello, necesitas saber qué código necesitas personalizar.

Puede simplificar el proceso copiando y modificando el código existente del tema principal. Puedes encontrar ese código utilizando la herramienta Inspect de Chrome o Firefox o copiándolo directamente del archivo CSS del tema padre.

Método 1: Copiar código desde el inspector de Chrome o Firefox

La forma más sencilla de descubrir el código CSS que necesitas modificar es utilizar las herramientas de inspección que vienen con Google Chrome y Firefox. Estas herramientas te permiten ver el HTML y CSS que hay detrás de cualquier elemento de una página web.

Puede leer más acerca de la herramienta inspector en nuestra guía sobre los fundamentos del elemento inspector: personalización de WordPress para usuarios DIY.

Cuando hagas clic con el botón derecho del ratón en tu página web y utilices el elemento inspeccionar, verás el HTML y el CSS de la página.

Al mover el ratón sobre diferentes líneas HTML, el inspector las resaltará en la ventana superior. También le mostrará las reglas CSS relacionadas con el elemento resaltado, de este modo:

Demonstrating how the Chrome inspect tool works

Puedes intentar editar el CSS ahí mismo para ver cómo quedaría. Por ejemplo, intentemos cambiar el color de fondo del cuerpo del tema a #fdf8ef. Encuentra la línea de código que dice cuerpo { y dentro de ella, el código que dice color:.

Sólo tienes que hacer clic en el icono del selector de color situado al lado de color: y pegar el código HEX en el campo correspondiente, de este modo:

Ahora, ya sabes cómo cambiar el color de fondo usando CSS. Para que los cambios sean permanentes, puede abrir su archivo style.css en el directorio del tema hijo (utilizando el gestor de archivos o FTP).

A continuación, pegue el siguiente código debajo de la información del tema hijo, de esta manera:

/*
Theme Name:   Twenty Twenty-One Child
Theme URI:    https://wordpress.org/themes/twentytwentyone/
Description:  Twenty Twenty-One child theme
Author:       WordPress.org
Author URI:   https://wordpress.org/
Template:     twentytwentyone
Version:      1.0.0
Text Domain:  twentytwentyonechild
*/

body {
    background-color: #fdf8ef
}

Este es el aspecto que tendrá si va al administrador de WordPress y abre Apariencia Editor de archivos de temas:

Adding custom CSS in a child theme's stylesheet in the theme file editor

Si eres principiante y quieres hacer otros cambios, te recomendamos que te familiarices con HTML y CSS para que sepas exactamente a qué elemento se refiere cada código. Hay muchas hojas de trucos de HTML y CSS en línea que puedes consultar.

Aquí está la hoja de estilos completa que hemos creado para el tema hijo. No dude en experimentar y modificarlo:

/*
Theme Name:   Twenty Twenty-One Child
Theme URI:    https://wordpress.org/themes/twentytwentyone/
Description:  Twenty Twenty-One child theme
Author:       WordPress.org
Author URI:   https://wordpress.org/
Template:     twentytwentyone
Version:      1.0.0
Text Domain:  twentytwentyonechild
*/

.site-title {
color: #7d7b77;
}
.site-description {
color: #aba8a2;
}
body {
background-color: #fdf8ef;
color: #7d7b77;
}
.entry-footer {
color: #aba8a2;
}
.entry-title {
color: #aba8a2;
font-weight: bold;
}
.widget-area {
color: #7d7b77;
}

Método 2: Copiar el código del archivo style.css del tema principal

Puede que haya muchas cosas en tu tema hijo que quieras personalizar. En ese caso, puede ser más rápido copiar algo de código directamente desde el archivo style.css del tema padre, pegarlo en el archivo CSS de tu tema hijo y luego modificarlo.

La parte complicada es que el archivo de hoja de estilos de un tema puede parecer realmente largo y abrumador para los principiantes. Sin embargo, una vez que entiendes lo básico, no es tan difícil.

Usemos un ejemplo real de la hoja de estilos del tema padre Twenty Twenty-One. Necesitas navegar a /wp-content/themes/twentytwentyone en tu carpeta de instalación de WordPress y luego abrir el archivo style.css en tu gestor de archivos, FTP o Editor de Archivos de Temas.

Verá las siguientes líneas de código:

:root {
/* Colors */
--global--color-black: #000;
--global--color-dark-gray: #28303d;
--global--color-gray: #39414d;
--global--color-light-gray: #f0f0f0;
--global--color-green: #d1e4dd;
--global--color-blue: #d1dfe4;
--global--color-purple: #d1d1e4;
--global--color-red: #e4d1d1;
--global--color-orange: #e4dad1;
--global--color-yellow: #eeeadd;
--global--color-white: #fff;
--global--color-white-50: rgba(255, 255, 255, 0.5);
--global--color-white-90: rgba(255, 255, 255, 0.9);
--global--color-primary: var(--global--color-dark-gray); /* Body text color, site title, footer text color. */
--global--color-secondary: var(--global--color-gray); /* Headings */
--global--color-primary-hover: var(--global--color-primary);
--global--color-background: var(--global--color-green); /* Mint, default body background */
--global--color-border: var(--global--color-primary); /* Used for borders (separators) */
}

Las líneas 3 a 15 controlan el tipo de colores (como amarillo, verde, púrpura) que usará todo el tema en sus códigos HEX específicos. Y luego, para líneas como ‘global-color-primary’ o ‘global-color-secondary’, eso significa que esos son los colores principales y secundarios de ese tema.

Puede copiar estas líneas de código en la hoja de estilos de su tema hijo y, a continuación, cambiar los códigos HEX para crear su combinación de colores perfecta.

A medida que se desplaza hacia abajo en la hoja de estilos del tema padre, se dará cuenta de que otras variables pueden tener estas variables de color, también, como aquí:

/* Buttons */
--button--color-text: var(--global--color-background);

Esto significa básicamente que todos los textos de los botones usarán el mismo color declarado en --global--color-background:, que es verde menta(--global--color-green: #d1e4dd). Si cambias el HEX en –global–color-green :, entonces el texto del botón también se verá diferente.

Nota: Si utiliza el tema hijo Twenty Twenty-One y no ve ningún cambio, es posible que tenga que actualizar la parte “Versión” de la información del archivo del tema (por ejemplo, de 1.0 a 2.0) cada vez que actualice el archivo style.css.

También puede seguir estos tutoriales para experimentar con la personalización de su tema hijo:

Cómo personalizar su tema infantil en bloque

Si utiliza un tema hijo en bloque, la mayoría de las personalizaciones se realizarán en el archivo theme.json, no en style.css.

Sin embargo, durante nuestras pruebas, encontramos que el proceso es complicado. A diferencia de los temas hijo clásicos, si eres nuevo en el desarrollo de temas de WordPress, hay una mayor brecha de conocimiento que necesitas llenar (especialmente acerca de JSON y cómo se maneja CSS allí).

Dicho esto, hemos encontrado una alternativa mucho más fácil usando el plugin Create Block Theme. Esta herramienta puede registrar cualquier cambio realizado en el Editor de Sitios Completo de WordPress en el archivo de tu tema hijo.json. Así, no tendrás que tocar ningún código en absoluto porque el plugin se encargará de ello por ti.

Vamos a mostrarle un ejemplo. En primer lugar, abra el Editor del sitio completo de WordPress yendo a Apariencia ” Editor.

Selecting the Full-Site Editor from the WordPress admin panel

Verás varios menús para elegir.

Aquí, sólo tienes que seleccionar “Estilos”.

Opening the Styles menu in Full Site Editor

En la página siguiente, verá varias combinaciones de estilos incorporados para elegir.

Para nuestro propósito, puede omitir todo eso y simplemente hacer clic en el icono del lápiz.

Clicking the Edit Styles button in the Full Site Editor

Ahora, intentemos cambiar algunas partes de tu tema hijo, como las fuentes.

Para este ejemplo, siga adelante y haga clic en “Tipografía” en la barra lateral derecha.

Clicking the Typography menu in Full Site Editor

A continuación, verá algunas opciones para cambiar las fuentes globales del tema para texto, enlaces, encabezados, leyendas y botones.

Hagamos clic en“Encabezados” para demostrarlo.

Clicking Headings in the Full Site Editor

En el menú desplegable Fuente, cambie la selección original por cualquier fuente disponible.

No dudes en cambiar el aspecto, la altura de las líneas, el espaciado entre letras y el tipo de letra si es necesario.

Styling headings in the Full Site Editor

Cuando hayas terminado, haz clic en “Guardar”. A continuación, puedes hacer clic en el botón Crear tema de bloque (el icono de la llave inglesa) situado junto a “Guardar”.

A continuación, haga clic en “Guardar cambios”. Esto guardará todos los cambios en el archivo child theme.json.

Saving a child block theme's changes using the Create Block Theme plugin

Si abre su archivo theme.json, verá los cambios reflejados en el código.

Esto es lo que vimos después de actualizar nuestro tema hijo:

A child block theme.json file after changes were made to it using the Create Block Theme plugin

Como puede ver, ahora el archivo incluye un código que indica que las etiquetas de encabezado utilizarán la fuente Inter con aspecto de semiondilla, altura de línea de 1,2, interlineado de 1 píxel y en minúsculas.

Por tanto, siempre que edites el tema hijo del bloque, asegúrate de hacer clic en el icono de la llave inglesa y guardar los cambios para que queden bien documentados.

Cómo editar los archivos de plantilla de un tema hijo

La mayoría de los temas de WordPress tienen plantillas, que son archivos de tema que controlan la estructura / disposición / diseño / plantilla de un área específica dentro de un tema. Por ejemplo, la sección del pie de página suele estar gestionada por el archivo footer.php, y la cabecera por el archivo header.php.

Cada tema de WordPress también tiene una estructura / disposición / diseño / plantilla diferente. Por ejemplo, el tema Twenty Twenty-One tiene cabecera, bucle de contenido, área de widget de pie de página y pie de página.

Si quieres modificar una plantilla, tienes que encontrar el archivo en la carpeta del tema padre y copiarlo en la carpeta del tema hijo. Después de eso, usted debe abrir el archivo y hacer las modificaciones que desee.

Por ejemplo, si usas Bluehost y tu tema padre es Twenty Twenty-One, entonces puedes ir a /wp-content/themes/twentytwentyone en tu gestor de archivos. A continuación, haz clic con el botón derecho en un archivo de plantilla como footer.php y selecciona “Copiar”.

Copying footer.php in Bluehost file manager

A continuación, introduzca la ruta del archivo de su tema hijo.

Una vez que haya terminado, simplemente haga clic en “Copiar archivos”.

Entering the child theme's file path to copy and paste the footer.php into inside Bluehost file manager

A continuación, se le redirigirá a la ruta del archivo.

Para editar el archivo footer. php, basta con hacer clic con el botón derecho del ratón y seleccionar “Editar”.

Editing footer.php in Bluehost file manager

Por ejemplo, quitaremos el enlace ‘Proudly powered by WordPress’ de la zona del pie de página y añadiremos allí un aviso de copyright.

Para ello, debe borrar todo lo que haya entre las etiquetas <div class="funciona con">:

<div class="powered-by">
				<?php
				printf(
					/* translators: %s: WordPress. */
					esc_html__( 'Proudly powered by %s.', 'twentytwentyone' ),
					'<a href="' . esc_url( __( 'https://wordpress.org/', 'twentytwentyone' ) ) . '">WordPress</a>'
				);
				?>
			</div><!-- .powered-by -->

A continuación, deberá pegar el código que encontrará debajo de esas etiquetas en el ejemplo siguiente:

<div class="powered-by">
<p>© Copyright <?php echo date("Y"); ?>. All rights reserved.</p>
</div><!-- .powered-by -->

Esto es lo que deberías tener ahora en el editor de texto:

Replacing the WordPress footer links in footer.php inside Bluehost file manager

Sigue adelante y guarda el archivo para hacer oficiales los cambios.

Después, visite su sitio web para ver el nuevo aviso de copyright.

Adding a dynamic copyright notice in footer.php

Cómo añadir nuevas funciones a su tema hijo

El archivo functions. php de un tema utiliza código PHP para añadir características o cambiar las características por defecto de un sitio WordPress. Actúa como un plugin para tu sitio WordPress que se activa automáticamente con tu tema actual.

Encontrarás muchos tutoriales de WordPress que te piden que copies y pegues fragmentos de código en functions.php. Pero si añades tus modificaciones al tema padre, entonces se sobrescribirán cada vez que instales una nueva actualización del tema.

Por eso recomendamos utilizar un tema hijo al añadir fragmentos de código personalizados. En este tutorial, vamos a añadir una nueva área de widgets a nuestro tema.

Podemos hacerlo añadiendo este fragmento de código al archivo functions.php de nuestro tema hijo. Para que el proceso sea aún más seguro, recomendamos utilizar el plugin WPCode para no editar directamente el archivo functions.php, reduciendo así el riesgo de errores.

Puede leer nuestra guía sobre cómo añadir fragmentos de código personalizados para obtener más información.

Aquí está el código que necesita para añadir su archivo functions.php:

// Register Sidebars
function custom_sidebars() {

$args = array(
'id'            => 'custom_sidebar',
'name'          => __( 'Custom Widget Area', 'text_domain' ),
'description'   => __( 'A custom widget area', 'text_domain' ),
'before_title'  => '<h3 class="widget-title">',
'after_title'   => '</h3>',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget'  => '</aside>',
);
register_sidebar( $args );

}
add_action( 'widgets_init', 'custom_sidebars' );

Una vez guardado el archivo, puede visitar la página Apariencia ” Widgets de su escritorio de WordPress.

Aquí verá su nueva área de widgets personalizados a la que podrá añadir widgets.

Creating a custom widget area for a child theme

Hay muchas otras características que puedes añadir a tu tema utilizando fragmentos de código personalizados. Marca / comprueba estos trucos extremadamente útiles para el archivo functions.php de WordPress y fragmentos de código de WordPress útiles para principiantes.

Cómo diagnosticar los problemas de su tema hijo de WordPress

Si nunca has creado un tema hijo, es muy probable que cometas algunos errores, y eso es normal. Por eso recomendamos usar un plugin de copia de seguridad y crear un sitio local o un entorno de ensayo para evitar errores fatales.

Dicho esto, no te rindas demasiado rápido. La comunidad de WordPress es muy ingeniosa, así que sea cual sea el problema que tengas, probablemente ya exista una solución.

Para empezar, puede comprobar los errores más comunes de WordPress para encontrar una solución.

Los errores más comunes que probablemente verás son errores de sintaxis causados por algo que se te ha pasado en el código. Encontrarás ayuda para resolver estos problemas en nuestra guía rápida sobre cómo encontrar y corregir el error de sintaxis en WordPress.

Además, siempre puedes empezar de nuevo si algo va muy mal. Por ejemplo, si accidentalmente borraste algo que tu tema padre requería, entonces puedes simplemente borrar el archivo de tu tema hijo y empezar de nuevo.

Esperamos que este artículo te haya ayudado a aprender a crear un tema hijo de WordPress. También puedes comprobar nuestra guía definitiva para aumentar la velocidad y el rendimiento de WordPress y nuestra selección experta de los mejores editores de arrastrar y soltar páginas para diseñar fácilmente tu sitio web.

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

98 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!

    • WPBeginner Support says

      You would want to use the code from our article below the text /* enqueue scripts and style from parent theme */ :)

      Administrador

  2. Yogesh Sambare says

    Hi, Team wpbeginner,
    Thanks for this awesome guide, now I think I’m able to make my themes child theme, and it’s really helpful for me .

  3. Ricardo says

    The line:
    “wp_get_theme()->get(‘Version’) )”

    Should be:
    “wp_get_theme()->get(‘Version’) )”

    cheers!

    • WPBeginner Support says

      While our comments automatically changed that in your message, we see the issue, thank you for letting us know :)

      Administrador

  4. Eitan says

    You need to add quotation marks to the Y = (“Y”) at the echo date, or you’ll get an error. – echo date(“Y”)

    • WPBeginner Support says

      You would update the parent theme as you normally would. For safety, you may want to create a backup before you update the parent theme in case there is a conflict somewhere.

      Administrador

  5. Mahesh Yadav says

    One thing I want to know, if we make a child theme then we have 2 CSS files to load one parent theme CSS and second child them CSS. Wouldn’t it increase the site load time and It added one more CSS to load?

  6. Marcos Flores says

    Hi! i’ve been reading this article and it works! but i also read wordpress documentation about this and they say this

    “Note that the previous method was to import the parent theme stylesheet using @import: this is no longer best practice, as it increases the amount of time it takes style sheets to load. The correct method of enqueuing the parent theme stylesheet is to add a wp_enqueue_scripts action and use wp_enqueue_style() in your child theme’s functions.php ”

    Should i use both method? or if i user the function.php i dont need to write import function inside style.css (located in my child-theme folder)

  7. Khema says

    Your instructions are missing a step with the functions.php creation. It should mention that needs to wrap the whole file. In this case I didn’t want to add the example you used and to another piece of code from the article you linked to. Naturally those codes didn’t include the php tag.

    Thanks for the article. It’s very very helpful.

  8. rReons says

    So question. I was using my wordpress theme without any child theme and was doing all the changes in to it. I have created a child theme thanks to your guide and I’m using that now as the website theme.

    My question is both themes have the same modifications changes. If I update the main theme from now on, will the changes affect the child theme also?

  9. balu says

    He! wpbeginner. WordPress official site saying this. You need to update the post. Thank You!

    Note that the previous method was to import the parent theme stylesheet using @import: this is no longer best practice, as it increases the amount of time it takes style sheets to load. The correct method of enqueuing the parent theme stylesheet is to add a wp_enqueue_scripts action and use wp_enqueue_style() in your child theme’s functions.php. You will therefore need to create a functions.php in your child theme directory. The first line of your child theme’s functions.php will be an opening PHP tag (<?php), after which you can enqueue your parent and child theme stylesheets. The following example function will only work if your Parent Theme uses only one main style.css to hold all of the css. If your child theme has more than one .css file (eg. ie.css, style.css, main.css) then you will have to make sure to maintain all of the Parent Theme dependencies.

  10. Alfonso de Garay says

    I have a Child theme with the theme latest version installed in my site. WP version 4.7.5. Received a notice that says WP version is available please update now.
    1. Do I have to backup my site again before updating?
    2. Do I have to create another Child theme using Child version 1 one?
    2. How can I change the Name, email and URL to Chile version 1

  11. Lisa Bruce says

    Hi, I can see that this video/post is a few years old, so I’m a little late to the party, but I have a questions I was hoping you could help me with.
    I am a relatively new to WP and just came to realize the importance of child themes. I have been working on developing a site for a friend and have made several changes to the theme that I am using. I found a bug in the theme and contacted the theme developer and they said that the bug had been fixed in a recent update.
    If I install the update I believe I will loose all my customizations. Is it too late to create a child them? Is it possible to do it now and then install the update? I prefer not to have to start from scratch.

    • WPBeginner Support says

      Hi Lisa,

      If you know what changes you made and to which files, then first download a backup of your existing theme to your computer. After that, install the updated version. You can now create a child theme and then copy and paste the code from your customized version to the child theme.

      Administrador

  12. Nell Yang says

    Thank you for this helpful post. I have always been looking for a video to show me how exactly should I use child theme. It is quite time consuming that each time after I updated my theme, all my styles just went away. It is frustrating to do everything over again. I tried to read the documents from wordpress but still don’t know how to proceed after activate the child theme. Keep up the good work! Thank you again!

  13. Tony Agee says

    Good instructional video. Most tutorials I have watched tell you to paste the code in the file but they neglect to tell you what medium to paste the code to. I was going to use Notepad++ but I guess you can use regular notepad.

  14. JP says

    Hello, i just want to say that you are a very good writer, very clear and simple. I past a long time on your article for learn WP.

    Thank you!

  15. Rob Brooks says

    Hi. Thank you for being a great WP resource. I am new to WP and really appreciate your guidance. I have followed the article to the letter but when I go to enable the child template on the site, I get the error “The parent theme is missing. Please install the “Real Estate Lite” parent theme. As you see I am using a free template called Real Estate light. it is located in the ../real-estate-lite/ directory of wp-content/themes. My code is below… did I do something wrong?

    Theme Name:   Real Estate Lite Child Theme
    Theme URI:    http://www.example.com/
    Description:  Real Estate Lite child theme
    Author:       me
    Author URI:   http://www.example.com
    Template:     Real Estate Lite
    Version:      1.0.0
    */
    @import url("../real-estate-lite/style.css");
    

    In addition, I will mention the theme was free and is running on WP version 4.7.2 (Running on Plesk). I created style.css file directly on the server so no FTP issues.

    I have already made significant changes to the parent style.css file as well as functions.php … I am not sure if this would affect this, but going to test on an unedited dummy domain to see if I get the same results

    Any guidance/assistance you can provide would be greatly appreciated.

  16. Carrie says

    Hi! Great article! I am finally starting to understand how to edit css so that I get the result I want, thanks to this article.

    Thanks much for the simplified explanation!

  17. Nalin says

    I created a child theme & Using @import for the “style.css” on a child theme. Now I want to change in another css file of parent theme’s folder ….. /font_awesome/css/fontawesome.css
    Now, I want to know that where I will put my new fontawesome.css in child theme & how to use @import command.
    or any other process to use more css file in child theme.

  18. Rebecca says

    So, I don’t have the wp content folder on my computer. What should I do?
    Should I have downloaded this at some point?

  19. Jean-philippe says

    I am learning so much since a few hours on your website. Everytime I search something in google related to “how to” in wordpress I find that the best information is here at WPbeginner. It is always well explained and easy to understand. I will always come back for information here without a doubt.

  20. Kevin says

    I know this will be a stupid question. I’m so new to this and have no skills at all. If I am creating a file, style sheet, etc. on my wp installation file on my local pc, how does that get onto my website? I guess I’m missing that? I use like 3 different PCs to work on my website and those local files aren’t on all of them. Again, I am sure I am missing something really dumb. Not seeing the connection.

  21. Francesco says

    Hi there,
    I’m following your tutorial but WordPress (4.5.3) doesn’t recognise the new folder on my online server. How can I work around this?
    Thanks,
    F.

  22. Carolina says

    Hi, thanks for the tutorial, very helpfull. But I have a question. Can I create a child theme from an already established website? I have a client who designed his own website but did not create a child theme. How to go about it?

  23. Mike says

    Thank you so much for the article and video. Apparently since these were created WordPress has new best practices listed in their codex which is confusing me.

    “The final step is to enqueue the parent and child theme stylesheets. Note that the previous method was to import the parent theme stylesheet using @import: this is no longer best practice.”

    Do I stick with the steps you outlined herein verbosely, or do I omit the import function and create the PHP file, or do I implement both?

    My theme’s style.css file only contains a header so importing that file seems irrelevant, and there are multiple CSS files like main.css located elsewhere in the parent’s file structure. Not knowing any better as a beginner I have already made changes to main.css to achieve some of my goals and only now I realize the child theme is necessary.

    Any advice is greatly appreciated.

    Best regards,

    Mike

  24. Olamide says

    Good day. When I did a live preview of the child theme, I noticed that it didn’t have the css of the parent theme. Maybe this is as a result of an error in the way I inserted the code?
    This is the code that I inserted:
    /*
    Theme Name: sparkling child
    Theme URI: https://www.wpbeginner.com/
    Description: sparkling child theme
    Author: djetlawyer
    Author URI: http://www.example.com
    Template: sparkling
    Version: 1.0.0
    */
    @import url(“../sparkling/style.css”);

    The parent theme is “sparkling”. If there is any error, please correct me.
    Thank you.

  25. lucia says

    Hi there,
    I am trying to set up a child theme to activate my footer on twenty twelve, but I don’t know what code to use to set it up.
    I tried this webpage

    with various suggestions , and I have tried to change your suggestion as given on twenty thirteen , but I don’t succeed.
    Could you please give me the right working code for setting up a child them for twelve twelve.

  26. Leigh says

    This was incredibly helpful – especially your HTML for us to copy. I’ve never been so excited to see colors change on a website before. This is easily the best “how-to” out there for this theme!

  27. Bhautik Andhariya says

    Hello, I have tried same example that you shown. But my child theme is replacing all the style of its parent theme.
    It doesn’t have any style of it’s parent. What is the solution? Can you please help me? I am new in wordpress and i am learning it.

  28. Angelo says

    Hi there!

    I’ve just installed the Bose template and also created a child theme for it. However, the following error message appears on the center of my website:

    Warning: implode(): Invalid arguments passed in /home/hello582/public_html/teste/wp-content/themes/bose/featured.php on line 12

    I’m a very beginner at websites creation, so I haven’t got any clue about what the problem is. Could anyone help me?

    Thanks a lot!

  29. Djamila says

    Hi,

    Thanks for the article! I could not get my child theme to ‘appear’ in the template section and it turned out I indeed misspelled the way the original template was named. What a difference a capital makes, huh?
    However, now that I have my child theme I was able to update the parent theme and when I did all of a sudden I got an issue with a super important plugin ( I am building a review blog on a local database, for now and it’s the wrap up/grading plugin belong to the template designers).
    In the parent template they ‘upgraded’ this plugin. I personally prefer the old one, but okay…anyway…underneath my review you now see *both*, the old wrap up with grades and the new one, which looks out of whack too. I have de-activated and re-activated but it stays like that. Super annoying and I don’t know where to look to either keep the old one (prettier) or only the new one and outlines as should.

    Where should I start? Thanks for any help you can give me.

  30. Amanda says

    Thanks for a great article!

    If I use a child theme, will I still be able to customize it using the Appearance> Theme Options that comes with my theme in the admin panel such as font size, background colors etc. or do I have to go the code route?

    If I have activated the Child theme and I use the Appearance tab to update the styling instead of using code, is it essentially still updating the parent theme because the related files are not in the child theme folder?

      • Amanda says

        Thanks for your reply.

        So if I activate the Child Theme and use the settings in the Appearance tab of my admin panel to change the styling (instead of writing css code), my changes won’t be overwritten when I do a theme or WordPress update on the parent theme?

        Would I still need to copy the stylesheet, header, footer files etc. to the child theme folder to make the scenario above work?

  31. Laura says

    I’ve been following these (and other) steps to create a child theme based on twentytwelve. The issue I’m running into is that wordpress seems to ignore only some of the css I’ve changed from the original theme and it’s driving me nuts. For example, I’ve successfully changed the background colour of the menu, but it simply won’t let me change the text colours of anything. I’ve used your approach of editing it in chrome’s code inspector thing (which worked great, the colour got changed, suggesting my code was correct) and pasting the changed code into the style.css of the child theme, but it doesn’t seem to get picked up at all. I don’t know what to do about this, any insights would be very welcome!

  32. Boyet says

    Thank you very much for this tutorial. I don’t have problem editing my child theme’s stylesheet, header, and footer files.

    My question is, what will I do if I wanted to change something in a file located in my mother theme’s folder like: public_html/wp-content/themes/shopera/woocommerce?

    Do I need to create the same path in my child theme?

    Thanks in advance…

  33. Tony Arnold says

    Very helpful and largely understood and executed.
    I am trying to make my header image full width.My theme doesn’t ‘allow’ this as standard so do i change the file?
    Thank you

  34. Xander says

    Hi, there!

    It seems I have got stuck a little bit. I have already made some changes in the some .php-files (e.g. header.php, footer.php and so on) of my parent theme without having a child theme installed.
    Now I want to create a child theme because updates of the parent one have been coming. What should I do with all those already modified files? Should I copy them in the child theme’s directory? What are folder I need to have it it? Should I create the same folders that the parent theme has got for the child theme?

    Thank you,

    • WPBeginner Support says

      You don’t need all the folders of your parent theme. You just need to recreate the files where you have made changes. We have a tutorial on how update themes without losing changes. It has a section where you can find out which files you have modified in your theme and what changes you have made to them.

      Download a fresh copy of your parent theme on your computer. Download the old theme to your computer and then upload the fresh copy. After that create a new child theme. Copy the files where you have made changes from the fresh theme to your child theme. Copy the changes you have made in the old theme files into the files of your new child theme.

      It would take some troubleshooting before you get it right. So we strongly recommend you to backup your site first. If possible test your changes on a local WordPress install first.

      Administrador

      • Xander says

        Thank you. Could you please give me a link on the tutorial mentioned?
        There is another obstacle – I have changed functions.php file, how can I reconcile both of them in the parent and child themes?

    • WPBeginner Support says

      Download your child theme to your computer. Create a zip file containing the theme folder. Go to the admin area of another site and then visit Appearance » Themes. Click on the add new theme button and then click on the upload button. Upload the zip file you created earlier. WordPress will extract and install your child theme.

      You will also need to install the parent theme as well.

      Administrador

  35. Daniel Garneau says

    Hello,

    I find this tutorial very useful to learn how to create a child theme. But in the process I made the following ajustments. There needs to be two files in the child-theme directory. They have to be named style.css and functions.php.

    style.css must contain at least (supposing one is using the TwentyTen theme):
    @import url(“../twentyten/style.css”);
    Template: twentyten

    When I consulted the turorial on 2015-05-12, the “template: twentyten” line was in the comment block. It must be a command that can be read by WordPress.

    Also, there must be a functions.php file, and it has to have minimally the following line of command :
    <?php

    Your tutorial along with the wp codex, helped me creating my first child theme. Thank you.

  36. Maria says

    Is it safe to say that the changes I made in the custom css field can be placed into my child’s theme style.css?

  37. Louise Mason says

    I am falling at the first fence – how do i find /wp-content/themes/? Actually where is the WordPress installation folder? In the video i can’t see what you click on or how you open it, the file manager just appears by magic!

      • Sonam says

        when I select the file manager of my web hosting account , I get four options :
        1)home directory
        2)web root
        3)public ftp root
        4)Document root

        which one should I select to work on.

        • Kylee says

          Hi – I go with Home Directory. That takes me to all the files. I click on Public HTML on the left to access my various sites. You probably figured it out at some stage but just in case you didn’t…

  38. Viju says

    Hi,

    I’m using a child theme for my website. What I’m struggling is to give a version to my style.css of the child theme. WordPress seems to append default wordpress version at the end of the file like /style.css?ver=4.1.1

    I’m incrementing the value of ‘version’ in my child’s style.css , but wordpress is not picking it.

    Because of this my changes to the child theme are not getting reflected to users who has the cached version of the css.

    can you advise how to handle this ?

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.