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

Hur man skapar ett WordPress barntema (Beginner’s Guide)

Barnteman är en av de WordPress-termer som ofta används och som gör nybörjare förvirrade. Du kanske till och med har hört talas om dem och bestämt dig för att hoppa över att skapa dem på grund av hur komplicerade de verkar.

Vi förstår det. Men enligt vår erfarenhet kan barnteman spara dig massor av huvudvärk på vägen. De skyddar dina värdefulla anpassningar, låter dig experimentera utan att förstöra din webbplats och gör det enkelt att uppdatera ditt tema.

Om du är intresserad har vi i denna nybörjarvänliga guide beskrivit hur ett barntema fungerar, hur du anpassar det och hur du gör ändringar i det.

How to Create a WordPress Child Theme

Hur fungerar ett barntema och varför behöver du det?

Ett barntema ärver alla funktioner, funktioner och stilar från ett annat WordPress-tema. När du skapar ett barntema anropas det ursprungliga temat som huvudtema.

Arvet inkluderar huvudtemats style.css-fil, som definierar temats huvudsakliga stil. Barntemat kan åsidosätta eller utöka sina ärvda egenskaper genom att lägga till egna filer eller genom att ändra de befintliga.

Även om det är möjligt att customize ditt WordPress-tema utan att installera ett barntema, finns det flera skäl till varför du kan behöva ett ändå:

  • Barnteman skyddar dina customizes under temauppdateringar och förhindrar att de skrivs över. Om du ändrar huvudtemat direkt kan dessa tweaks försvinna när du uppdaterar.
  • Med barnteman kan du på ett säkert sätt testa nya designer eller funktioner utan att förstöra webbplatsens ursprungliga tema, på samma sätt som med en staging-miljö.
  • Om du vet hur man kodar kan barnteman göra utvecklingsprocessen mer effektiv. Filerna för ett barntema är mycket enklare än för ett huvudtema. Du kan fokusera på att bara ändra de delar av huvudtemat som du vill ändra eller förstora.

Vad du ska göra innan du skapar ett WordPress barntema

Vi har sett många användare av WordPress som är glada över att dyka in i det tekniska, bara för att bli avskräckta när error dyker upp. Vi förstår det. Det är därför det är viktigt att veta vad du ger dig in på innan du skapar ett barntema.

Här är några saker som vi rekommenderar att du gör först innan du fortsätter med denna Step-by-Step guide:

  1. Var medveten om att du kommer att arbeta med kod. Du behöver åtminstone en grundläggande förståelse för HTML, CSS, PHP och, valfritt, JavaScript för att förstå vilka ändringar du behöver göra. Du kan läsa mer om detta i WordPress Theme Handbook.
  2. Välj ett överordnat tema som har den design och de funktioner som du vill ha på webbplatsen. Om möjligt, hitta ett tema där du bara behöver göra ett fåtal ändringar. Om det behövs kan du följa vår checklista över saker att göra innan du byter WordPress-tema.
  3. Använd en lokal site eller en staging site för att utveckla teman. You don’t want to create unintentional errors on your live site.
  4. Säkerhetskopiera din webbplats först. Vi rekommenderar att du använder ett plugin för säkerhetskopiering som Duplicator om det är första gången du gör det.

Det finns flera sätt att skapa ett barntema från ditt befintliga tema. Ett är med manuell kod, medan andra kräver ett plugin, vilket är mycket mer nybörjarvänligt.

Den första metoden kan verka skrämmande om du saknar teknisk erfarenhet. Men även om du väljer en av metoderna med tillägg rekommenderar vi ändå att du läser igenom den manuella metoden för att bekanta dig med processen och de filer som är inblandade.

Pro tips: Vill du customize ditt tema utan att skapa ett barntema? Använd WPCode för att säkert aktivera nya funktioner med custom code snippets utan att förstöra din website.

Med all detta i åtanke, låt oss gå vidare till hur man skapar ett barntema i WordPress. Du kan hoppa till den metod du föredrar med hjälp av länkarna under:

Metod 1: Skapa ett barntema för WordPress manuellt

Först måste du öppna /wp-content/themes/ i din WordPress-installationsfolder.

Du kan göra detta genom att använda filhanteraren på ditt webbhotell WordPress eller en FTP-klient. Vi tycker att det första alternativet är mycket enklare, så vi kommer att använda det.

Om du är en Bluehost-kund kan du logga in på dashboarden för ditt webbhotell och navigera till tabben ”Websites”. Efter det klickar du på ”Settings”.

Bluehost site settings

På tabben Overview rullar du ner till sectionen ”Quick Links”.

Välj sedan ”File Manager”.

Bluehost File Manager button

I det här skedet måste du gå till din websites public_html folder och öppna sökvägen /wp-content/themes/.

Här klickar du bara på knappen ”+ Folder” i det övre vänstra hörnet för att skapa en new folder för ditt barntema.

Creating a new folder in Bluehost file manager

Du kan döpa foldern till vad du vill.

För denna tutorial kommer vi bara att använda namnet på mappen twentytwentyone-child eftersom vi kommer att använda Twenty Twenty-One som vårt huvudtema. När du är klar klickar du bara på ”Create New Folder”.

Naming a new child theme file in Bluehost file manager

Därefter måste du öppna den folder du just skapat och klicka på ”+ File” för att skapa den första filen för ditt barntema.

Om du använder en FTP-klient kan du använda en textredigerare som Notepad och uploada filen senare.

Creating a new file in Bluehost file manager

Gå vidare och namnge den här filen ’style.css’, eftersom det är ditt barns huvudsakliga stylesheet och kommer att innehålla information om barntemat.

Klicka sedan på ”Create New File”.

Creating a new stylesheet file in Bluehost file manager

Nu högerklickar du bara på filen style.css.

Därefter klickar du på ’Edit’ för att öppna en ny tabs som i screenshot nedan.

Editing a style.css file in Bluehost file manager

I denna new tabs kan du klistra in följande text och anpassa den efter yours behov:

/*
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
*/

När du är klar klickar du bara på ”Save Changes”.

Saving a stylesheet file in Bluehost file manager

Nästa sak du behöver göra är att skapa en andra fil och döpa den till functions.php. Den här filen kommer att importera eller ställa stylesheets i kö från huvudtemats filer.

När du har skapat dokumentet, add to följande wp_enqueue-kod:

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
    );
}

När du är klar sparar du bara filen som i föregående steg.

Note : För denna metod rekommenderar vi att du läser den officiella dokumentationen för barnteman och inkluderande filer för att se till att ditt barntemas stylesheets laddas korrekt.

Du har nu skapat ett mycket grundläggande barntema. När du går till Utseende ” Teman i din WordPress-adminpanel bör du se alternativet Twenty Twenty-One Child.

Klicka på knappen ”Activate” för att börja använda barntemat på din site.

Activating a child theme in WordPress admin

Metod 2: Skapa ett klassiskt barntema med ett plugin

Nästa metod använder pluginet Child Theme Configurator. Detta användarvänliga WordPress-plugin låter dig skapa och customize WordPress barnteman snabbt utan att använda kod, men det fungerar bara bra med ett klassiskt (icke-block) theme.

Det första du behöver göra är att installera och aktivera WordPress plugin. När du har aktiverat det måste du navigera till Tools ” Child Themes i din WordPress dashboard.

På tabben Parent/Child blir du ombedd att välja en action. Välj bara ”CREATE a new Child Theme” för att komma igång.

Creating a new child theme with Child Theme Configurator

Välj sedan ett huvudtema från en dropdown-meny. Vi kommer att selecta temat Hestia.

Efter det klickar du bara på knappen ”Analyze” för att se till att temat är lämpligt att använda som huvudtema.

Choosing a parent theme in Child Theme Configurator

Därefter kommer du att bli ombedd att namnge den folder som barntemat ska sparas i. Du kan använda vilket namn på folder du vill.

Under det måste du välja var du ska spara de nya stilarna: i den primära stylesheet eller en separat.

Den primära stylesheet är den standardtema stylesheet som medföljer ditt barntema. När du sparar new customizers till den här filen ändrar du direkt huvudstilarna i ditt barntema. Varje ändring kommer att skriva över det ursprungliga temats stil.

Alternativet separator allow you to save a new custom style to a separate stylesheet file. Detta är användbart om du vill bevara det ursprungliga temats stil och ej skriva över den.

För demonstrationsändamål väljer vi det första alternativet. Men när du blir mer kreativ med dina customizes för barntema kan du alltid upprepa den här processen och välja det andra alternativet.

Choosing where to save the stylesheet in Child Theme Configurator

När du går neråt måste du välja hur huvudtemats stylesheet ska nås.

Vi kommer bara att välja standardinställningen ”Använd invänta [granskning] / kö” för WordPress, eftersom det låter pluginet bestämma lämpliga actions automatiskt.

Choosing the parent theme stylesheet handling in Child Theme Configurator

När du kommer till steg 7 måste du klicka på knappen märkt ”Click to Edit Child Theme Attributes”.

You can then fill in the details of your child theme (du kan sedan fylla i detaljerna för ditt barntema).

Filling out the child theme details in Child Theme Configurator

När du skapar ett barntema manuellt kommer du att förlora huvudtemats menyer och widgetar. Child Theme Configurator kan kopiera dem från huvudtemat till barntemat. Kontrollera boxen i steg 8 om du gillar att göra detta.

Slutligen klickar du på knappen ”Create New Child Theme” för att skapa ditt nya barntema.

Clicking the Create New Child Theme button in Child Theme Configurator

Tillägget kommer att skapa en folder för ditt barntema och add to style.css och functions.php filerna som du kommer att använda för att customize temat senare.

Innan du aktiverar temat bör du clicka på länken högst upp på vyn för att få en preview och se till att det ser bra ut och inte förstör din site.

Previewing a child theme in Child Theme Configurator

Om allt verkar fungera klickar du på knappen ”Activate & Publicera”.

Nu kommer ditt barntema att gå live.

I det här skedet kommer barntemat att se ut och bete sig exakt som huvudtemat.

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

Metod 3: Skapa ett barntema för block med ett tillägg

Om du använder ett block-tema erbjuder WordPress ett enkelt sätt att skapa ett barntema med pluginet Create Block Theme.

Först måste du installera och aktivera WordPress plugin. Därefter går du till Appearance ” Create Block Theme.

Här väljer du helt enkelt ”Skapa ett barn till [aktuellt temanamn]”.

Creating a child theme with Create Block Theme plugin

Därefter fyller du i informationen om ditt barntema. Vi använder Twenty Twenty-Four i det här exemplet, så vi kommer att namnge det Twenty Twenty-Four Child.

Vi gav också en beskrivning och författare för barntemat. När du är klar klickar du på knappen ”Skapa barntema”.

Inserting the child block theme's information in the Create Block Theme plugin

Plugin-programmet kommer nu att skapa och installera zip-filen för WordPress-temat i ditt adminområde.

När du har gjort det kommer din webbplats automatiskt att aktivera detta nyskapade barntema. Du kan bekräfta detta genom att gå till Utseende ” Teman.

Seeing the newly created child theme made with the Create Block Theme plugin

Bonus Tips: Ta reda på om ditt theme har en generator för barntema

Om du har tur kan det hända att ditt WordPress tema redan har en befintlig funktion för att skapa ett barntema.

Om du till exempel använder Astra kan du gå till Astra Child Theme Generator website. Efter det fyller du bara i namnet på ditt barntema och klickar på knappen ”Generera”.

Astra Child Theme Generator website

Din webbläsare kommer då automatiskt att downloada ditt barntema till din dator, som du sedan själv kan installera på WordPress.

Vi hittade också några andra populära WordPress-teman som har en generator för barnteman:

Hur man customize ditt klassiska barntema

Note : Detta section är för användare av klassiska teman i WordPress. Om du använder ett block theme, hoppa bara till nästa section.

Tekniskt sett kan du anpassa ditt barntema utan kod genom att använda Theme Customizer. De ändringar du gör där kommer inte att påverka ditt huvudtema. Om du inte är bekväm med kodning ännu, kan du gratis använda Customizer.

Med detta sagt rekommenderar vi också att du customize barntemat med kod.

Förutom att lära sig mer om WordPress temautveckling, tillåter kod customize att ändringarna dokumenteras i barntemats filer, vilket gör det lättare att spåra dem.

Nu är det mest grundläggande sättet att customize ett barntema genom att lägga till custom CSS i filen style.css. För att göra det måste du veta vilken kod du behöver customize.

Du kan förenkla processen genom att kopiera och ändra den befintliga koden från huvudtemat. Du kan hitta den koden genom att använda Chrome eller Firefox Inspect tool eller genom att kopiera den direkt från huvudtemats CSS-fil.

Metod 1: Kopiera kod från Chrome- eller Firefox-inspektören

Det enklaste sättet att upptäcka den CSS-kod som du behöver ändra är att använda de inspektörsverktyg som följer med Google Chrome och Firefox. Dessa tools allow you to look at the HTML and CSS behind any element of a web page.

Du kan läsa mer om inspektörsverktyget i vår guide om grunderna i inspect element: customize WordPress för DIY-användare.

När du högerklickar på din page och använder inspect-elementet får du se HTML och CSS för sidan.

När du för musen över olika HTML-rader kommer inspektören att markera dem i fönstret högst upp. Den kommer också att visa dig CSS-reglerna relaterade till det markerade elementet, gillar så här:

Demonstrating how the Chrome inspect tool works

You can try editing the CSS right there to see how it would look. Låt oss till exempel prova att ändra bakgrundsfärgen för temats body till #fdf8ef. Hitta kodraden som säger body { och inuti den, koden som säger color: .

Klicka bara på färgväljarikonen bredvid färg : och klistra in HEX-koden i lämpligt fält, gillar så här:

Nu vet du hur du ändrar bakgrundsfärgen med hjälp av CSS. För att göra ändringarna permanenta kan du öppna din style.css-fil i barntemats directory (med filhanteraren eller FTP).

Klistra sedan in följande kod under informationen om barntema, gillar så:

/*
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
}

Så här kommer det att gilla om du går till WordPress-admin och öppnar Appearance Theme File Editor:

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

Om du är Beginner och vill göra andra ändringar rekommenderar vi att du bekantar dig med HTML och CSS så att du vet exakt vilket element varje kod hänvisar till. Det finns många HTML- och CSS-fuskark på nätet som du kan använda dig av.

Här är den kompletta stylesheet som vi har skapat för barntemat. Experimentera gärna och ändrades gratis:

/*
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;
}

Metod 2: Kopiera kod från huvudtemats style.css-fil

Det kanske finns en hel del saker i ditt barntema som du vill customize. I så fall kan det vara snabbare att kopiera lite kod direkt från huvudtemats style.css-fil, klistra in den i ditt barntemas CSS-fil och sedan ändra den.

Det knepiga är att ett temas stylesheet-fil kan se väldigt lång och överväldigande ut för Beginnare. Men när du väl förstår grunderna är det faktiskt inte så svårt.

Låt oss använda ett verkligt exempel från huvudtemat Twenty Twenty-One’s stylesheet. Du måste navigera till /wp-content/themes/twentytwentyone i din WordPress-installationsfolder och sedan öppna filen style.css i din filhanterare, FTP eller Theme File Editor.

Du kommer att se följande rader med kod:

: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) */
}

Raderna 3 till 15 kontrollerar vilken typ av färger (gillar gult, grönt, lila) som hela temat kommer att använda i sina specifika HEX-koder. Och sedan, för rader som ”global-color-primary” eller ”global-color-secondary”, betyder det att det är de primära och sekundära färgerna för det temat.

You can copy these lines of code to your child theme’s stylesheet and then change the HEX codes to create your perfect colorschema.

As you scroll down in the parent theme’s stylesheet, you will notice that other variables may have these color variables, too, like here:

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

Detta innebär i princip att all text på knappar kommer att använda samma färg som deklareras i --global--color-background:, vilket är mintgrönt (--global--color-green: #d1e4dd). Om du ändrar HEX i --global--color-green: kommer texten på knappen också att se annorlunda ut.

Note : Om du använder barntemat Twenty Twenty-One och inte ser några ändringar kan du behöva uppdatera ”Version”-delen av temafilinformationen (till exempel från 1.0 till 2.0) varje gång du uppdaterar filen style.css.

Du kan också följa dessa tutorials för att experimentera med customizes för ditt barntema:

Hur man Customize ditt Block barntema

Om du använder ett child block-tema kommer de flesta av dina anpassningar att göras i filen theme.json, inte i style .css.

Under vår testning fann vi dock att processen var komplicerad. Till skillnad från klassiska barnteman finns det en större kunskapslucka som du måste fylla i (särskilt om JSON och hur CSS hanteras där) om du är new till WordPress tema utveckling.

Som sagt, vi hittade ett mycket enklare alternativ med hjälp av Create Block Theme plugin. Detta verktyg kan posta alla ändringar som görs i WordPress Full Site Editor i ditt barntema.json-fil. Så du behöver inte röra någon kod all eftersom pluginet kommer att ta hand om det åt dig.

Låt oss visa dig ett exempel. Först öppnar du WordPress Full Site Editor genom att gå till Appearance ” Editor.

Selecting the Full-Site Editor from the WordPress admin panel

Du kommer att se flera menyer att välja mellan.

Här väljer du bara ”Styles”.

Opening the Styles menu in Full Site Editor

På nästa page ser du flera kombinationer av built-in-stilar att välja mellan.

För vårt ändamål kan du helt enkelt hoppa över alltihop och bara clicka på pencil icon.

Clicking the Edit Styles button in the Full Site Editor

Låt oss nu försöka ändra några delar av ditt barntema, till exempel teckensnitten.

I det här exemplet går du vidare och klickar på ”Typografi” i den högra sidebaren.

Clicking the Typography menu in Full Site Editor

Därefter kommer du att se några alternativ för att ändra temats globala teckensnitt för text, länkar, rubriker, bildtexter och knappar.

Låt oss klicka på ”Rubriker” för demonstrationens skull.

Clicking Headings in the Full Site Editor

I dropdown-menyn Font ändrar du det ursprungliga valet till valfritt font som är available.

Ändra gratis utseendet, line height, bokstavsavstånd och bokstavsinlägg om det behövs.

Styling headings in the Full Site Editor

När du är klar klickar du bara på ”Save”. Efter det kan du klicka på knappen Create Block Theme (ikonen med skiftnyckeln) bredvid ”Save”.

Klicka sedan på ”Spara ändringar i temat”.

Saving changes made to a child theme with the Create Block Theme plugin

Därefter går du vidare och väljer vilka ändringar som ska sparas i barntemat.

Exempel på detta är teckensnitt, anpassade stilar, malländringar med mera.

Selecting what changes to save to the child theme with the Create Block Theme plugin

När du har gjort det är det bara att scrolla hela vägen ner i sidofältet.

Klicka sedan på ”Spara ändringar”.

Clicking on the Save Changes button in the Create Block Theme plugin

Låt oss nu visa filen theme.json så att du kan se ändringarna återspeglas i koden.

För att göra detta klickar du på knappen Create Block Theme igen och väljer ”View theme.json”.

Clicking to view the theme.json file in the Create Block Theme plugin

När du har klickat på den ser du att filen innehåller några nya kodtillägg.

I vårt fall innehåller filen kod som anger att rubriktaggar ska använda teckensnittet Inter med halvfett utseende, 1,2 radhöjd, 1 pixels radavstånd och i gemener.

Viewing the theme.json file in the Create Block Theme plugin

Så när du redigerar ditt barntema, se till att klicka på ikonen med skiftnyckeln och save dina ändringar så att de är väldokumenterade.

Hur man redigerar ett barntemas templates filer

De flesta WordPress-teman har mallar, som är temafiler som styr design och layout för ett specifikt område i ett tema. Exempelvis hanteras sidfoten vanligtvis av filen footer.php, och sidhuvudet hanteras av filen header.php.

Varje WordPress-tema har också en annan layout. Temat Twenty Twenty-One har till exempel ett sidhuvud, en innehållsslinga, ett widgetområde i sidfoten och en sidfot.

Om du vill ändra en template måste du hitta filen i mappen för huvudtemat och kopiera den till mappen för barntemat. Efter det ska du öppna filen och göra de ändringar du vill.

Om du till exempel använder Bluehost och ditt huvudtema är Twenty Twenty-One, kan du gå till /wp-content/themes/twentytwentyone i din filhanterare. Högerklicka sedan på en template-fil som gillar footer.php och välj ”Copy”.

Copying footer.php in Bluehost file manager

Efter det, enter filvägen för ditt barntema.

När du är klar klickar du bara på ”Copy Files”.

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

You will then be redirect to the file path.

För att editera filen footer.php högerklickar du bara på den och väljer ”Edit”.

Editing footer.php in Bluehost file manager

Som ett exempel kommer vi att ta bort länken ”Proudly powered by WordPress ” från footern area och lägga till en copyright notice där.

För att göra det bör du delete allt mellan <div class="powered-by"> tags:

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

Sedan måste du klistra in koden som du hittar under dessa taggar i exemplet nedan:

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

Så här ska du nu ha det i textredigeraren:

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

Gå vidare och save filen för att göra ändringarna officiella.

Efter det kan du besöka din website för att se det nya copyright notice.

Adding a dynamic copyright notice in footer.php

Så här lägger du till ny funktionalitet i ditt barntema

Filen functions.php i ett theme använder PHP-kod för att lägga till funktioner eller ändra standardteman på en WordPress site. Det gillar ett plugin för din WordPress-webbplats som aktiveras automatiskt med ditt nuvarande theme.

Du hittar många WordPress tutorials som ber dig att copy and paste code snippets till functions.php. Men om du addar dina ändringar till huvudtemat kommer de att skrivas över när du installerar en new update till temat.

Det är därför vi rekommenderar att du använder ett barntema när du lägger till anpassade code snippets. I denna tutorial kommer vi att add a new widget area to our theme.

Vi kan göra det genom att lägga till detta code snippet i vårt barntemas functions.php-fil. För att göra processen ännu säkrare rekommenderar vi att du använder pluginet WPCode så att du inte redigerar filen functions.php direkt, vilket minskar risken för error.

Du kan läsa vår guide om hur du lägger till custom code snippets för mer information.

Här är koden som du behöver add to din functions.php fil:

// 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' );

När du har saved filen kan du besöka sidan Appearance ” Widgets i din WordPress dashboard.

Here, you will see your new custom widget area that you can add wid gets to.

Creating a custom widget area for a child theme

Det finns massor av andra funktioner som du kan add to your theme med hjälp av custom code snippets. Kontrollera dessa extremt användbara tricks för WordPress functions.php-filen och användbara WordPress code snippets för nybörjare.

Så här felsöker du ditt WordPress barntema

Om du aldrig har skapat ett barntema tidigare finns det en god chans att du kommer att göra några misstag, och det är normalt. Det är därför vi rekommenderar att du använder ett plugin för säkerhetskopiering, skapar en lokal webbplats eller en staging-miljö och använder dummy-innehåll för din demo-webbplats.

Med allt detta sagt ska du inte ge upp för snabbt. WordPress-communityn är mycket resursstark, så oavsett vilket problem du har finns det förmodligen redan en lösning.

Till att börja med kan du kontrollera våra vanligaste WordPress error för att hitta en lösning.

De vanligaste error du förmodligen kommer att se är syntaxfel som orsakas av något du missat i koden. Du hittar hjälp med att lösa dessa issues i vår snabbguide om hur du hittar och fixar syntaxfel i WordPress.

Dessutom kan you alltid börja om från början om något går väldigt fel. Om du till exempel råkade ta bort något som var obligatoriskt för ditt huvudtema kan du helt enkelt radera filen från ditt barntema och börja om.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du skapar ett WordPress-barntema. Du kanske också vill kolla in vår ultimata guide om hur du testar ditt WordPress-tema mot de senaste standarderna och vår jämförelse mellan gratis och premium WordPress-teman.

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.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

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.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

104 kommentarerLämna ett svar

  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. Oyatogun Oluwaseun Samuel says

    I love the flexibility offered by child theme in that when there’s an update of the parent theme, the changes made in the child theme are maintained. Also I also love to manually create child theme as I believe doing it that way may expose me to mistakes which will in turn increase my understanding and expertise. We learn when we make mistakes.

  3. Chris says

    I never really gave child themes much thought, thinking they weren’t necessary. Before reading this article, I didn’t realize that customized functions are removed from the functions.php file when the theme is updated. For me, a child theme is a must if I use a theme from WordPress theme repository. Thanks for this informative article!

    • Dayo Olobayo says

      Great point about child themes. There’s also another option to consider though… Some premium themes offer customization panels that avoid the need for code edits altogether. However, child themes gives more flexibility in the long run especially if you’re comfortable with a little code.

  4. Hajjalah says

    Thanks for this comprehensive guide. I would like to create a child theme using the plugin method but still have some not sure about some issues.
    Will the codes in the WPCode plugin take effect on the child theme? If the parent theme is updated but the child theme is not updated, Can’t they conflict to cause an error?

    • WPBeginner Support says

      Yes the code in WPCode will appear on your child theme and if you update the parent theme there is a chance of conflict but it is not a guarantee.

      Administratör

  5. Jiří Vaněk says

    A child theme is always the first thing I create on a newly installed site. Although I try to use WP Code a lot and avoid problems, but the child theme is an absolutely brilliant thing when updating a template and can save a lot of trouble with lost code that disappears from the main template after an update.

    • WPBeginner Support says

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

      Administratör

  6. 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 .

  7. 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 :)

      Administratör

  8. 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”)

  9. Bomo says

    So now that we have created a child theme, how do we update the parent theme when the child theme is activated?

    • 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.

      Administratör

  10. 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?

    • WPBeginner Support says

      While the load time would technically increase, it shouldn’t be by a noticeable amount.

      Administratör

  11. Daniel Waduka says

    I am just starting to use child themes, and this article has been of so much help to me.

    Thanks so much.

  12. 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)

  13. 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.

  14. 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?

  15. 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.

  16. 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

    • WPBeginner Support says

      Hi Alfonso,

      WordPress updates normally do not affect your themes so you do not need to create another child theme. You should always backup your website before updating WordPress.

      Administratör

  17. 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.

      Administratör

  18. 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!

  19. 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.

  20. 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!

  21. 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.

    • WPBeginner Support says

      Hey Rob,

      You will need parent theme to be installed on your site and Template value should match parent theme’s actual name which you can see in it’s style.css file.

      Administratör

  22. 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!

  23. 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.

  24. 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?

  25. 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.

  26. 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.

  27. 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.

  28. 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?

  29. 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

  30. 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.

  31. 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.

  32. 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!

  33. 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.

  34. 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!

  35. 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.

  36. 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?

  37. 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!

  38. 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…

  39. 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

  40. 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.

      Administratör

      • 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.

      Administratör

Lämna ett svar

Tack för att du väljer att lämna en kommentar. Tänk på att alla kommentarer modereras enligt våra policy för kommentarer, och din e-postadress kommer INTE att publiceras. Vänligen använd INTE nyckelord i namnfältet. Låt oss ha en personlig och meningsfull konversation.