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

Beginner’s Guide to Pasting Snippets from the Web into WordPress

Vill du lära dig hur du klistrar in snippor från webben i WordPress?

Vi publicerar många WordPress tutorials som ber användare att add code snippets till WordPress.

Att copy and paste kod i WordPress theme-filer kan verka enkelt för erfarna användare, men det kan vara skrämmande för nybörjare.

I den här artikeln visar vi hur du kan copy and paste code snippets från webben till WordPress utan att förstöra din site.

Beginner's guide to pasting snippets from the web into WordPress

Varför addera code snippets till din site i WordPress?

WordPress är världens bästa website-byggare på grund av den flexibilitet den erbjuder. Det är superenkelt att add new funktioner och funktionalitet till din site och kan hjälpa till att bygga nästan alla typer av webbplatser.

Vi delar med oss av allsköns tips och tricks som du kan använda för att göra din website bättre. Vissa av dessa tips kommer att be dig att add to kod till WordPress.

Att lägga till customize code snippets på din website är valfritt, och du kan ofta hitta tillägg som gör samma sak, men ibland är ett enkelt snippet mer effektivt.

Ofta kan tillägg av code snippets vara ett enkelt sätt att fixa många vanliga WordPress error, förbättra din WordPress säkerhet och add new funktioner till din website.

Med detta sagt, låt oss ta en titt på hur du på ett säkert sätt kan add to code snippets till din WordPress website.

Vilka är de bästa sätten att add to code snippets i WordPress?

Det är viktigt att nämna att innan du börjar lägga till code snippets till din WordPress website, bör du installera och använda en WordPress backup plugin.

På så sätt är din WordPress site säker och du kan alltid återställa den från en backup om något skulle gå fel.

När du lägger till snippets till WordPress, kan du hitta instruktioner för att lägga till dem till WordPress temats templates filer, gillar index.php, single.php, och mer.

Dessa snippets är endast användbara för dessa specifika temafiler, så du måste add to dem direkt eller skapa ett WordPress barntema.

De flesta code snippets kommer dock att läggas till i ditt WordPress temas functions.php-fil. Vissa tutorials kan rekommendera att lägga till det direkt i filen, men det finns mycket bättre alternativ som allow you att framtidssäkra dina ändringar.

På så sätt om du någonsin ändrar ett theme, kommer din customize funktionalitet ej att tas bort.

Det finns olika sätt att editera WordPress-filer beroende på vilken metod du väljer för att add to custom code snippets till din WordPress blogg eller website.

Med det sagt, låt oss ta en titt på några av de mest nybörjarvänliga sätten att add to custom code snippets i WordPress.

Metod 1: Lägga till Custom Code med WPCode Plugin (Easy)

Att använda ett code snippets plugin är det säkraste och mest nybörjarvänliga sättet att add code till WordPress.

WPCode - Best WordPress Code Snippets Plugin

WPCode plugin låter dig lägga till och hantera custom code snippets på din webbplats enkelt, utan att behöva edit dina theme filer.

Den levereras med smarta code snippet bekräftelse för att hjälpa dig att förhindra vanliga code errors. Detta skyddar dig från att förstöra din website när du lägger till code snippets.

WPCode har också ett built-in kodbibliotek som gör det enkelt att hitta alla de mest populära code snippets för WordPress. Du kan add to dessa expertskrivna code snippets med bara några clicks.

Det bästa är att det låter dig hantera alla code snippets från en central vy, och du kan till och med organisera dem med hjälp av taggar.

Den gratis versionen av WPCode kommer med allt du behöver för att add to custom code i WordPress. WPCode Pro erbjuder avancerade funktioner som gillar ett privat moln snippet bibliotek, conversion Pixels, tidsinställda snippets, och mer.

Note: WPCode-metoden är användbar för snippets som behöver addas till functions.php-filen. Om du blir ombedd att add a code snippet in other theme files, då fungerar inte den här metoden.

Hur man editerar och addar kod till WordPress med WPCode

Om du ska använda WPCode plugin för att lägga till kod till WordPress, kommer du att lägga till kod direkt i WordPress adminpanelen.

Först måste du installera och aktivera det gratis pluginet WPCode. För mer detaljer, se vår guide för nybörjare om hur du installerar ett plugin för WordPress.

Efter aktivering, gå bara till Code Snippets ” + Add Snippet i din WordPress adminpanel. Sedan klickar du på knappen Add New.

Click 'Add New Snippet' in WPCode

Då kommer du till en vy där du kan välja ett snippet från det färdiga biblioteket eller add to din custom code.

För att add to custom code, click on the Use snippet button under alternativet ”Add Your Custom Code (New Snippet)”.

Add custom code in WPCode

På nästa vy kan du börja med att ge ditt snippet ett namn som hjälper dig att komma ihåg det. Klistra sedan in din kod i boxen. Se till att du väljer korrekt code type i rullgardinsmenyn till höger.

Paste custom snippet and choose code type

Därefter rullar du ner till ”Insertion” section. Här kan du välja att använda code snippet som en shortcode som du manuellt kan copy and paste var som helst på din site.

Choose insertion option for code snippet

Eller så kan du selecta metoden ”Auto Insert” för att välja en location (WordPress-funktion) där code snippet ska infogas automatiskt.

You can choose from locations such as Run Everywhere, Front-end Only, Admin Only, Site Wide Header, After Post, Between Posts, Before Paragraph, and more.

Auto insert locations in WPCode

Det bästa med WPCode är att notis från de olika Auto Insert-alternativen, det kommer också med nybörjarvänliga villkorliga logiska alternativ. Detta låter dig select när din kod ska hämtar.

WPCode Smart Conditional Logic

När du är klar med att lägga till koden, toggle omkopplaren från ”Inaktiverad” till ”Aktiv” i det övre högra hörnet.

Klicka sedan på knappen Save Snippet (Spara snippet ).

Save and activate code snippet

När snippet är aktivt läggs det till automatiskt eller visas som shortcode, beroende på vilken metod för insert du har valt.

För detaljerade instruktioner, se vår guide om hur du enkelt lägger till custom code snippets i WordPress.

Så här addar du kod till Header och Footer i WordPress

Ibland kan du bara behöva add to kod till ditt temas header.php- eller footer.php -filer. Tillägget WPCode kan också hjälpa dig att göra detta enkelt.

Detta är praktiskt när du behöver add to en tracking-kod för Google Analytics, Google AdSense, Facebook Pixel, TikTok Pixel med mera till din website.

Dessutom låter det dig hantera alla dina header- och footer-koder på ett ställe, förhindrar manuella error och låter dig uppgradera eller ändra ditt theme utan bekymmer.

Note: Denna metod fungerar bäst för tracking-skript, customize CSS och JavaScript-kod.

Gå till Code Snippets ” Header & Footer och enter sedan ditt code snippet i header, body eller footer, section på din website.

Add code to header and footer with WPCode

Se till att du clickar på knappen ”Save Changes”, så kommer dina code snippets att vara live på din website.

För mer details, se vår guide om hur man lägger till header- och footer-kod i WordPress.

Metod 2: Lägga till Custom Code i Site-Specific WordPress Plugin

Create site specific plugin

Ett annat flexibelt alternativ är att använda ett site-specifikt WordPress plugin. Detta är ett custom plugin som du kan skapa för din egen website och använda för att save all your custom code.

Fördelen med den här metoden är att din kod inte är beroende av ditt theme, och den kommer att förbli aktiv även när du byter themes. Den påverkas inte heller av eventuella updates av WordPress på din website.

Note: Denna metod är endast tillämplig för code snippets som måste addas till filen functions.php.

Om du använder ett site-specifikt plugin kan du använda den built-in WordPress plugin editor för att lägga till din custom code.

Först måste du gå till Tillägg ” Plugin Editor och sedan välja ditt plugin från rullgardinsmenyn märkt ”Välj plugin för att editera:”.

Editorn kommer att hämta ditt site-specifika plugin. Sedan kan du helt enkelt add code to the page.

Add code to site specific plugin

När du är slutförd, se till att du klickar på knappen ”Update File” för att spara dina ändringar.

Om något saknas i din kod eller kan förstöra din website, kommer plugin editor automatiskt att ångra dina ändringar.

Ett annat sätt du kan add to custom code till ett site-specifikt plugin är genom att använda FTP. För mer detaljer, se vår guide för nybörjare om hur du använder FTP för att uploada filer till WordPress.

Öppna bara din website med den FTP-klient du föredrar och högerklicka sedan på filen med tillägget och välj alternativet ”View/Edit”.

Edit site-specific WordPress plugin using FTP

Detta öppnar filen så att du kan add to dina code snippets. När du savear och uploadar filen igen kommer ändringarna att visas automatiskt.

För mer detaljer, se vår guide om hur du skapar ett site-specifikt plugin för din website.

Metod 3: Lägga till Custom Code till Functions.php eller andra Theme Templates

Add code to functions.php example

Slutligen är det okej att add code snippets direkt till ditt temas functions.php-fil. Vi rekommenderar dock att du använder de andra alternativen ovan, eftersom det finns vissa nackdelar.

För det första, om du updaterar ditt WordPress theme, kommer all your changes att försvinna.

Därefter kommer koden du addade bara att fungera om du använder det vissa temat.

Med detta sagt, låt oss ta en titt på hur man korrekt copy and paste code snippets och undvika att bryta din website.

Om du lägger till code snippets direkt till ditt temas functions.php-fil eller någon annan page template, kan du lägga till koden genom att navigera till Appearance ” Theme Editor i din WordPress adminpanel.

Sedan kan du selecta filen i den högra columnen, så öppnas den i editorn.

Add code to functions.php and other templates

Den tutorial du följer kommer att berätta var du kan lägga till kod snippet, men om ej, då måste du lägga till koden längst ner i filen under all kod som finns.

Ett annat alternativ är att använda FTP i filhanteraren på ditt WordPress webbhotell för att add custom code till dina theme-filer.

Anslut bara till din FTP-klient till din website och gå sedan till wp-content ” themes ” your-theme-folder och högerklicka på filen som behöver editeras.

Edit theme files via FTP

Sedan klickar du på alternativet ”View/Edit” för att öppna filen i textredigeraren och add to code snippet.

Felsökning av PHP-fel när du lägger till Custom Code

Det finns några vanliga misstag som Beginnare gör när de lägger till custom code snippets på sina WordPress websites. Lyckligtvis kan de flesta av dessa error undvikas och fixas enkelt.

Låt oss ta en titt på dessa error och de bästa sätten du kan fixa dem.

1. Felaktig användning av PHP Begin and End Tags

WordPress är huvudsakligen skrivet i programmeringsspråket PHP som har en specifik syntax som talar om för din server att följande kod måste bearbetas av PHP. Så här ser ett typiskt PHP code snippet ut:

// PHP Begin Tag
<?php
  
// Rest of the code goes here
  
// PHP End Tag
?>

All din PHP-kod måste vara inuti taggarna <?php och ?>.

PHP end tagged är mycket viktigt i filer som växlar fram och tillbaka mellan PHP och HTML. Detta inkluderar de flesta WordPress theme-filer som använder PHP-tags tillsammans med HTML.

Du måste se till att om du klistrar in din kod på en location där PHP start taggen inte är close, så måste du add to din kod utan den inledande PHP taggen.

<?php
// Some pre-existing code
 
// your custom code
 
?>

Om du klistrar in din custom code utanför eller efter PHP end taggen, måste du add to PHP begin taggen också.

<?php
// Some pre-existing code
?> 
 
// Your custom code snippet
<?php 
 
?>

Nästan 90% av alla error orsakas av felaktig placering av PHP start- eller sluttaggar. Att klura på din kod hjälper dig att förstå om eller ej du behöver add to PHP start- eller sluttaggar i ditt custom code snippet.

Men många WordPress temafiler som functions.php kanske inte har en PHP end tagged kl. Det innebär att du kan add to din kod längst ner i filen utan start- eller sluttaggar.

Här är ett exempel på hur det gillar att se ut.

<?php
// Lots of code in your theme's functions.php file
//
//
// Your custom code
function custom_loginlogo() {
echo '<style type="text/css">
h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; }
</style>';
}
add_action('login_head', 'custom_loginlogo');

Kom ihåg att vissa tutorials kan förutsätta att du redan vet hur man använder PHP start- och sluttaggar. Så de kan helt enkelt visa dig ett code snippet utan dessa tags på plats.

function custom_loginlogo() {
echo '<style type="text/css">
h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; }
</style>';
}
add_action('login_head', 'custom_loginlogo');

Ibland när code snippets ges kan de addas till flera locations, så PHP:s slut- och starttaggar kommer inte att inkluderas.

När du lägger till ett sådant code snippet i dina theme-filer måste du se till att det är inuti PHP-taggarna.

2. Felaktiga nestnings error

PHP har en viss syntax för funktioner, villkorlig logik och loopar. Denna syntax beror på hakparenteser som anger när en funktion börjar och när den slutar.

Här är till exempel en enkel PHP-funktion:

<?php
function wpbeginner_tutorial() {
echo "Hello World!";
}
?>

Nu, om du vill add to ett custom code snippet som inte har något att göra med den här funktionen, då måste du lägga den utanför den här funktionen gillar detta:

// Pre-existing code in your theme file
<?php
function wpbeginner_tutorial() {
echo "Hello World!";
}
// Your custom code
function custom_loginlogo() {
echo '<style type="text/css">
h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; }
</style>';
}
?>

Om du missar de inledande eller avslutande hakparenteserna kommer koden att brytas och du kommer att få upp en page error.

Förstå PHP error i WordPress

Fel som orsakas av att lägga till custom code till WordPress kommer ofta att resultera i ett detaljerat error message. De flesta av dem är syntaxfel, parse-fel eller fatal errors på grund av oväntade tecken.

Den goda nyheten är att dessa error kommer att tala om för dig vilken rad i din kod som orsakade felet.

PHP error code example

Sedan kan du gå till den exakta raden för att reviewera koden och ta reda på vad du missade.

För detta rekommenderar vi att du använder en riktig textredigerare för kodredigering eftersom de har radnummer och syntaxmarkering som kan hjälpa dig att fixa problemet enkelt.

Om du använder WPCode plugin, kommer det också med exakt felrapportering som visar dig den exakta raden där ett error uppstod.

WPCode error reporting

När WPCode hittar ett error som kan hindra dig från att komma åt din website admin area, kommer det automatiskt att inaktivera snippets så att du säkert kan fixa problemet.

Vad gör du när din WordPress site är otillgänglig?

Först och främst, ta ett djupt andetag och få inte panik. Alla filer på din website finns kvar och du kan komma åt dem.

Anslut bara till din website med en FTP-klient eller filhanteringsappen i cPanel på ditt WordPress webbhotell account.

För mer detaljer, se vår guide för nybörjare om hur du använder FTP för att uploada filer till WordPress.

Leta sedan upp filen där du addade koden som orsakade error och öppna den för att editera den.

Sedan kan du försöka fixa problemen med code snippet. Om du inte kan fixa dessa problem tar du bara bort kod snippet du addade och sparar dina ändringar.

Nu bör din site vara tillbaka till det normala igen. Om den fortfarande visar något error, downloadar du en ny kopia av ditt WordPress theme och extraherar zip-filen till din dator.

Därefter lokaliserar du filen där du gjorde ändringarna tidigare och uploadar den till din server samtidigt som du skriver över den gamla filen.

För fler sätt att lösa dessa problem, se vår guide om de vanligaste WordPress-felen och hur man fixar dem. Om det inte hjälper, följ vår guide för felsökning i WordPress för att utföra en steg-för-steg-diagnos.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du klistrar in code snippets från webben till WordPress. Du kanske också vill se vår guide om hur du skapar en gratis email address för företag och våra val av de bästa programvarorna för chattsupport för småföretag.

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

43 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. Dayo Olobayo says

    I was always afraid of adding codes to my themes so as not to damage my website. But I’ve read many articles on this forum and I usually see the recommendation of the wpcode plugin. I don’t have an idea about code but this plugin has made it easy for me to style my website using code snippets, and even more confidently too.

    • Dayo Olobayo says

      I do have a question though. Does wpcode allows the styling of themes that is done under the ”additional css” option of wordpress themes?

      • WPBeginner Comments says

        If you are asking about adding CSS via WPCode, then yes. WPCode can help add CSS code as well.

        That said, depending on your needs the additional CSS section may be better for adding theme CSS.

  3. Max says

    Thanks for the article but it’s really thrown my understanding of the functions.php file. Is a closing tag really required on every theme’ s Functions file. For example, looking at a clean, untouched installation of the popular Divi theme, there is no closing php tag: ?>
    Divi works perfectly without this closing tag so I am assuming that some themes’ Functions.php files don’t require it?

    Another point – many people giving out snippets (yourself included) include line numbers as part of the code. When the code snippets are pasted into the functions.php file you then need to go through each line deleting the line numbers, and only the line numbers. If you don’t do this the code breaks and won’t work. I expect this is a very common mistake too. So it would be preferable to avoid these potential problems by posting the code in your tutorials without the line numbers so we don’t have to tediously edit the line numbers out after pasting and risk corrupting the code.

    • WPBeginner Support says

      Hey Max,

      Good questions. You are right, it is not necessary to add the closing php tag at the end of the functions file.

      As for line numbers in code snippets, you will notice a tiny menu when you take your mouse over to a code snippet on WPBeginner. This menu contains a view source or copy button. Clicking on it will open a popup window where you can copy the raw code without line numbers.

      Hope this helps.

      Administratör

  4. Mayaprakash Pant says

    I read this article and it is really nice. Just to know one thing, what are the sentences written in green in above tutorial? Are they comments or something else? Help me with this.

  5. Charlesdeeds says

    Thank you my dear for your support. you have saved a brother from loosing he’s job appointment… Thanks and Best regards

  6. Dylan Cornelius says

    You’ve done a wonderful job describing a somewhat technical topic in an easy-to-understand, straightforward way. Your examples are simple and really help. Kudos!

  7. Asanka Ranjeewa says

    It is really help full, even i am knowing a little codding. it is really help full and now i know it even better. thanks.

  8. Anna says

    I’m laughing out loud because it’s as if you’d written the article based on the mistakes I just made! Thank you so much for spelling out the little details as I was quickly back up and running thanks to this article.

  9. Aashi says

    Whenever i comment and uncomment the codes it creates an error sometimes of ”;” or sometimes of ”/”.
    I again uploaded the file in which there were no changes but still the same error occurs.
    Stuck badly.. What to do next.

  10. Keli says

    Help! I just made one of the mistakes mentioned above and my site is broken. I saw your reply to Amy but can’t figure out how to change my function php. Please help!

    • Keli says

      I have a child theme installed and activated, and I added google analytics code to ‘Appearance> Editor> Theme Functions (functions.php) which was empty and now my site is broken? its a huge issue as there si currently facebook promo running driving people to a broken site.

    • WPBeginner Support says

      Hi Amy,

      You will need access to cPanel dashboard for your web hosting account or FTP credentials. Once you have those, you can connect to your WordPress site using FTP or you can use File Manager from your hosting account dashboard. Locate your theme’s functions.php file and edit it. You will need to go to line 14 to remove the unexpected code or remove the code that you entered earlier causing the issue.

      Administratör

  11. isi says

    hi i tried to paste a font on php, im newbie on this below is the code can anyone see which is my mistake….

    <html >

    <link rel="Shortcut Icon" href="/images/favicon.ico ” type=”image/x-icon” />
    <link rel="pingback" href="” />
    <?php
    wp_head();

  12. Jessica says

    So using the example above, please could you advise which tags would be stripped from your code snippet below, if you were to paste the code into an existing functions.php file that already had an opening and closing tag?

    // Paste your Google Analytics code from Step 4 here

  13. Jeffrey says

    I pasted the code to update the date and time of when a post was updated rather than it displaying the ”original” date of the post. I posted right after the Google authorship in my Genesis Child Theme. It’s displaying the updated date but it doesn’t say ”Updated. . . ”, it just shows the original date and underneath shows the updated date. The file starts with in the file, so my thinking is I have too many ”php” in the code. I’m sure it is not placed inside another function. Any help would be greatly appreciated. Here is the code:

    add_action(’genesis_before_post_content’, ’add_last_modified_date’);
    function add_last_modified_date() {
    if (is_single()) { ?>
    <time datetime="”>
    <?php }
    }

    This is the code BEFORE where I placed the above code:

    960, ’height’ => 80 ) ); ** commented out by payam 09-06-11 to add my own logo and header bg

    /** Add support for 3-column footer widgets **/
    add_theme_support( ’genesis-footer-widgets’, 3 );

    /* ACF Options page */
    if(function_exists(’acf_add_options_page’)) {

    acf_add_options_page( ’Site Options’ );
    // acf_add_options_sub_page(’Header’);
    // acf_add_options_sub_page(’Footer’);

    }

    /* payam add google publisher authorship info to home page only */
    add_action(’genesis_meta’, ’child_google_publisher_authorship’);
    function child_google_publisher_authorship() {
    if ( is_front_page() ) {
    $ED_google_publisher_authorship_link = ” ;
    }
    echo $ED_google_publisher_authorship_link;
    }

  14. Barbara says

    Am I the only one wondering if my google analitics information can be pasted into my WordPress.com site??? In the past I’ve come across things suggested to be added to WordPress only to find out it does not work for my .com. So tell me. Did I go through all of the analitics set up for nothing? I hope not. Where could you paste the information in WordPress.com? There no place to be found.

  15. Louis Sahagun says

    I was informed that I have to add script to the beggining of: /google_analytics_auto.js’/script/head> in order to change this from relative url to absolute url. This will fix many broken links since I recently changed the IDX to my site. After reading the above instructions, it sounds like I need to use a FTP client like Filezilla to perform this. Is this correct?

  16. Anthony says

    Hello,

    I found your tutorial unfortunately after I broke my site. I am getting this error:

    Parse error: syntax error, unexpected T_IF in /home/content/45/7334345/html/wp-content/themes/Magazine110613/functions.php on line 31

    But I cannot access the admin panel to fix the code. Any suggestions?

    Thanks!

    • WPBeginner Support says

      You can fix this by accessing your site using an FTP client like Filezilla. Download a fresh copy of your theme and extract it on your computer, then you need to upload the new functions.php file from your computer to to your theme directory using the FTP client.

      Administratör

  17. Dwight B says

    Hi I was referred to your article from this link:

    http://cyberchimps.com/guide/make-responsive-unresponsive/

    I have a question, since I have my child theme installed and activated, is adding the PHP code as simple as going to ’Appearance> Editor> Theme Functions (functions.php) [which is empty]’ and pasting it?

    Or are there other files that need to be edited?

    Thanks, hope you can help.

    • Editorial Staff says

      It is that simple, but you have to be very careful with the proper syntax that we have highlighted in the article above. If you paste the code incorrectly, then you can potentially lock yourself out of your WordPress admin. This is why we highly recommend that you know how to use FTP before modifying code through WordPress admin.

      Administratör

  18. Sean says

    Wow, this is the 1st ever article I have seen on the web which acknowledges the fact that newbies who want to get things done with adding code do not necessarily know the assumptions that tutorial writers often have.

    This is a very thoughtful and great gesture on your part. Thank You.

    I do not blame the experts since they are writing form another level, but seriously, it wouldn’t hurt them or take any extra time to just add the 1 or 2 lines to make sure their code is understood by everyone.

    Right now I am looking around for the explanation of another basic thing that must be obvious to all the PHP pros but is totally lost on me, which is, what do they mean when they say ”Paste the code below within the single.php within the loop” . . .

    What’s ”within the loop” here and where should I paste the code snippet in my single.php file ?

    Any ideas please ?

    • WPBeginner Support says

      Sean, in WordPress terminology, the loop refers to the WordPress Loop. It is the code that runs a loop, generating HTML for posts fetched by the SQL query run by WordPress. It starts like this:

      <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

      and ends like this:

      <?php endwhile; else: ?>
      <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
      <?php endif; ?>

      When you are asked to paste a snippet inside the loop you need to paste it between the start and end of the loop.

      Administratör

  19. Michael says

    Nice, thoughtful article. There are many little things a beginner must know, like these simple errors, that are quickly taken for granted once we learn them. It’s these little things that often cause people to just give up. But that keeps some of us in business :-).

  20. Greg says

    Thanks for this – the one questions that I have is that often I have seen that there are ’code snippets’ that are offered, but I have NO idea which file they are to be pasted into!

    Others, like the one that talks about Displaying Custom Fields here:
    http://codex.wordpress.org/Using_Custom_Fields#Displaying_Custom_Fields

    The links to ”The Loop” quickly get very unclear when they make statements like:
    The Loop should be placed in index.php
    and
    ……..in any other Templates used to display post information.<=== they must be kidding, right?

    This is where I get very frustrated. How am I supposed to know what "Any of the OTHER Templates used to display post information" is supposed to mean.

    Any guidance you could give on this would be greatly appreciated.

    • Editorial Staff says

      Hey Greg,

      It is definitely a tough question as to where to paste the code because the answer varies based on the situation. If it is a theme based function, then you would use functions.php file (or another theme file). If it is a site based function, then you probably want to use a site-specific plugin.

      The Loop is used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code contained in the Loop will be processed on each post. You read more about it here: http://codex.wordpress.org/The_Loop

      As for template files, you can get a better overview here: http://codex.wordpress.org/Template_Hierarchy#Visual_Overview

      Not all themes have all these template files. The most basic theme only needs style.css file and an index.php file. But the more customization you want, the more options you have available for you. The visual overview in the link above should explain that.

      ”The loop should be placed in index.php” is the very bare bone example. Some themes have separate loop files altogether (i.e loop.php or loop-content.php, loop-quote.php etc). Then the theme author would call those loop files into other template files like single.php where they can say get_template_part( ’loop’, ’single’ ); which will include the loop-single.php file. Theme authors have different practices to make things work. It also depends on whether you are using a parent theme or a child theme. Because in child themes, you are mainly just working with the functions.php file and hooks available in the theme framework. Yes it gets pretty tricky when it comes to the child themes.

      Administratör

  21. Felipe says

    In your very first example:

    //This is the opening tag of a PHP Code
    <?php

    the comment *before* the opening tag of a PHP Code won't run very well ;) Not a big deal as few people will paste that anywhere but as the whole guide is about learning how to mix PHP code correctly with HTML and other PHP code …

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.