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

Så här addar du en shortcode i WordPress (Beginner’s Guide)

Tänk dig att kunna lägga till nya saker på din WordPress-webbplats, som bildspel, kontaktformulär eller till och med speciallistor, bara genom att skriva en enkel kod. Det är det som är kraften i kortkoder.

Du kommer att upptäcka att många WordPress-plugins och teman kan använda kortkoder för att lägga till extra funktioner på din webbplats. Många av våra läsare frågar oss hur man på bästa sätt lägger till dem i sina inlägg, sidor och sidofält.

I den här artikeln visar vi dig hur du använder kortkoder på din WordPress-webbplats, steg för steg. Vi visar dig även hur du skapar egna kortkoder om du vill vara riktigt kreativ.

How to add a shortcode in WordPress

Vad är shortcodes?

Shortcodes i WordPress är kodgenvägar som hjälper dig att add to dynamiskt content till WordPress posts, pages och sidebar widgetar. De visas inom hakparenteser och gillar det här:

[myshortcode]

För att bättre förstå shortcodes, låt oss ta en titt på bakgrunden till varför de lades till i första hand.

WordPress filtrerar allt innehåll för att se till att ingen använder posts och pages innehåll för att inserta skadlig kod i databasen. Det innebär att du kan skriva grundläggande HTML i dina posts, men du kan inte skriva PHP-kod.

Men vad händer om du vill köra lite custom code inuti dina posts för att visa related posts, bannerannonser, kontaktformulär, gallerier eller något annat?

Det är här Shortcode API kommer in i bilden.

I grund och botten tillåter det utvecklare att add to sin kod i en funktion och sedan registrera den funktionen med WordPress som en shortcode, så att användare enkelt kan använda den utan att ha någon kodningskunskap.

När WordPress hittar shortcoden kommer den automatiskt att runna den kod som är kopplad till den.

Låt oss se hur du enkelt kan add shortcodes till dina posts och pages i WordPress. Du kan använda länkarna under för att hoppa till din önskade metod.

Lägga till en shortcode i WordPress Posts och Pages

Först måste du editera det post och den page där du vill add to shortcoden.

Efter det måste du klicka på knappen Lägg till block ’+’ för att infoga ett Shortcode-block.

Add a shortcode block

När du har lagt till Shortcode-blocket kan du helt enkelt enter din shortcode i blockinställningarna.

Shortcode kommer att tillhandahållas av olika WordPress tillägg som du kanske använder, t.ex. WPForms för kontaktformulär eller OptinMonster för e-postmarknadsföring.

Enter your shortcode

Om du vill veta mer om hur du använder block kan du läsa vår Gutenberg tutorial för mer details.

Du kan nu save din post eller page och previewa dina ändringar för att se shortcoden i action.

Lägga till en shortcode i WordPress Sidebar Widgets

Du kan också använda shortcodes i WordPress sidebar widgets.

Besök bara sidan Appearance ” Widgets och lägg till ett ’Shortcode’ widgetblock i en sidebar.

Add a shortcode widget block

Nu kan du klistra in din shortcode i widgets text area.

Glöm inte att klicka på knappen ”Update” för att spara dina inställningar för widgetar.

Enter shortcode in widget block

Efter det kan du besöka din WordPress website för att se live preview av shortcode i sidebar widget.

Lägga till en shortcode i gamla WordPress Classic Editor

Om du fortfarande använder den gamla klassiska Editorn i WordPress, så här kan du lägga till shortcodes till dina WordPress posts och pages.

Du behöver bara editera den post och page där du vill add to shortcoden. Du kan klistra in shortcoden var som helst i content editorn där du vill att den ska visas. Se bara till att shortcoden står på en egen rad.

Add shortcode to classic editor

Glöm inte att save dina ändringar. Efter det kan du previewa din post och page för att se shortcoden i action.

Lägga till en shortcode i WordPress Theme Files

Shortcodes är avsedda att användas i WordPress-poster, pages och widgets. Ibland kan du dock vilja använda en shortcode i en fil för ett WordPress theme.

WordPress gör det enkelt att göra det, men du måste editera dina WordPress theme-filer. Om du inte har gjort det förut, se vår guide om hur du copy and paste kod i WordPress.

I grund och botten kan du lägga till en shortcode till alla WordPress temamallar genom att helt enkelt lägga till följande kod:

<?php echo do_shortcode('[your_shortcode]'); ?>

WordPress kommer nu att leta efter shortcode och visa dess utdata i din template för temat.

Lägga till en shortcode i Block Theme-filer med Full-Site Editor

Om du använder ett block editor-tema är det lättare att add shortcodes i dina WordPress Theme-filer med hjälp av hela Site Editor.

Du kan komma åt detta verktyg genom att välja Appearance ” Editor från WordPress dashboard.

Du kommer att visas ditt temas hemmamall som standard, och du kan byta till andra templates genom att välja alternativet ”Templates”.

Choosing a Template to Edit in the Full Site Editor

När du har valt en template kan du börja edit:a den genom att click:a i den högra rutan i editorn. Editorn kommer nu att fylla hela vyn.

Nu kan du klicka på ikonen ’+’ block inserter och search efter shortcode-blocket. Därefter drar du det helt enkelt till templaten och skriver in den shortcode du vill använda.

Adding a Shortcode Block in the Full Site Editor

Glöm inte att klicka på knappen ”Save” högst upp på vyn för att spara dina ändringar.

Skapa din egen customize shortcode i WordPress

Shortcodes kan vara riktigt användbara när du vill add to dynamiskt content eller custom code i WordPress post och pages. Om du vill skapa en customize shortcode är det dock obligatoriskt med viss kodningserfarenhet.

Om du är bekväm med att skriva PHP-kod, så finns här en exempelkod som du kan använda som template:

// function that runs when shortcode is called
function wpb_demo_shortcode() { 
 
// Things that you want to do.
$message = 'Hello world!'; 
 
// Output needs to be return
return $message;
}
// register shortcode
add_shortcode('greeting', 'wpb_demo_shortcode');

I den här koden skapade vi först en funktion som runar lite kod och returnerar utdata. Därefter skapade vi en new shortcode med anropet ”greeting” och sa till WordPress att runna den funktion vi skapat.

Du kan lägga till den här koden i ditt temas functions.php-fil manuellt eller använda ett code snippet plugin som WPCode.

Adding Code to WPCode

För mer details, you can see our guide to adding custom code in WordPress without breaking anything.

Följer du detta kan du add to shortcoden till dina posts, pages och widgetar med hjälp av följande kod:

[hälsar]

Den kommer att runna den funktion you skapade och visa önskad output.

Låt oss nu ta en titt på en mer praktisk användning av en shortcode.

I det här exemplet kommer vi att visa en Google Adsense-banner i en shortcode:

// The shortcode function
function wpb_demo_shortcode_2() { 
 
// Advertisement code pasted inside a variable
$string .= '<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-format="fluid"
     data-ad-layout="in-article"
     data-ad-client="ca-pub-0123456789101112"
     data-ad-slot="9876543210"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>';
 
// Ad code returned
return $string; 
 
}
// Register shortcode
add_shortcode('my_ad_code', 'wpb_demo_shortcode_2'); 

Glöm inte att ersätta annonskoden med din egen annonskod.

Du kan nu använda shortcoden [my_ad_code] i dina posts, pages och sidebar widgets i WordPress. WordPress kommer automatiskt att runna den funktion som är kopplad till shortcoden och visa reklamkoden.

Shortcodes vs. Gutenberg Blocks

Vi får ofta frågor från användare om skillnaderna mellan shortcodes och Gutenberg blocks.

I grund och botten tillåter block dig att göra samma sak som shortcodes men på ett mer användarvänligt sätt.

Istället för att obligatoriskt lägga till en shortcode för att visa dynamiskt innehåll, allow blocks användare att lägga till dynamiskt innehåll i posts/pages med ett mer intuitivt användargränssnitt. Många populära tillägg till WordPress har gått över till att använda block istället för shortcodes eftersom de är mer nybörjarvänliga.

Vi har sammanställt en lista över de mest användbara Gutenberg block plugins för WordPress som du kanske vill prova.

Om du vill skapa dina egna customize Gutenberg block kan du följa vår Step-by-Step tutorial om hur du skapar customize Gutenberg block i WordPress.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du addar en shortcode i WordPress. Du kanske också vill se vår guide om hur du skapar ett custom WordPress theme utan att skriva någon kod och vårt expertval av de bästa drag and drop WordPress page builder plugins.

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

103 kommentarerLämna ett svar

  1. Mrteesurez

    Thanks, the guide you share helped to create my own shortcode using the format you shared in the post. That means I can add any code to the part where you said ”things you want to do”. Is it compulsory I add only PHP code, can I add a working HTML code there ?

    • WPBeginner Support

      With how the code is currently set up you would need to add PHP and if you wanted a different language like HTML you would need to make some tweaks.

      Administratör

  2. Andrew Wilson

    Hi Guys,

    Is it possible with this plugin to create a unique QR Code for users that sign up to your website?

    i.e. a person registers on the website, and as part of that process the back-end creates a unique QR Code for that user which if scanned by a third party takes them to their profile on the website?

  3. Moinuddin Waheed

    This is very helpful for making our own custom short codes.
    I have been using short codes for a while and have thought of making my own short codes to use but was not aware about the process.
    I have a bit of coding knowledge and can easily make shortcodes through php functions.
    Thanks for the guide.

    • WPBeginner Support

      You’re welcome, glad our guide was helpful :)

      Administratör

  4. Jiří Vaněk

    Thank you for the detailed instructions. I was able to add the shortcode to Gutenberg but could not use it as a php code. At the same time, it is evidently that simple. A bit smarter again thanks to wpbeginner.

  5. Mohammed

    In Example2 How did you define this shortcode ’my_ad_code’ thought you didn’t define it as a function?

    • WPBeginner Support

      That is added with the code add_shortcode at the bottom of the example :)

      Administratör

      • Mohammed

        ❤️❤️
        Appreciate for the best Article

  6. Josh

    One picture says ”greatings” instead of ”greetings” ;)

    • WPBeginner Support

      Thank you for pointing that out, it works as a good reminder to make sure you spell your shortcodes correctly :)

      Administratör

  7. Maya

    Thanks for sharing such a detailed article keep up the good work!

    • WPBeginner Support

      You’re welcome, glad you found our guide helpful!

      Administratör

  8. abuzar

    your guidence is very easy to learn. thanks you

    • WPBeginner Support

      You’re welcome!

      Administratör

  9. Hugh

    Thanks for the great article. Works like a charm. However, although it is explained on the page link provided in the article, it may have been helpful to many readers if you had reiterated that to create shortcodes yourself (’How to Create Your Own Custom Shortcode’ section of the article), you simply add the example code provided or your own code to the theme’s (or child theme’s) ’functions.php’ file. Thanks again! :)

    • WPBeginner Support

      Thank you for that feedback! :)

      Administratör

  10. Hafed benchellali

    Thank you for this great article!

    • WPBeginner Support

      You’re welcome!

      Administratör

  11. Susan Benfatto

    Thank you for your tutorial, it was very useful

    • WPBeginner Support

      Glad it was helpful :)

      Administratör

  12. Rohmah Azim

    Hi
    Can you tell me how I can add shortcode to my header?

    • WPBeginner Support

      You would need to use the method for the theme files from this article and add it to your theme’s header file.

      Administratör

  13. David

    -Hi, you know if its possible to add a box fixed for example with a shortcode inside? TNX

    • WPBeginner Support

      That would depend on the plugin you are using for the shortcode.

      Administratör

  14. Tihomir

    Hi All
    in one of my pages I am using this shortcode [product_category category=’jeans’ number=’1000′ per_page=’1000′] . It shows 1000 products of the chosen category jeans. What I can add to this code to make this 1000 products appear same like on product category page or by with a load more button?

  15. Jose Rodriguez

    English translation –> but something happens when I add the shortcode and then some text, it turns out that this text is inside the html of the shortcode in the frontend, how can I avoid that?

  16. loganathan

    I am creating an own theme, the problem is that theme does no support shortcode. can anyone help me to enable shortcode functionality for my theme.

  17. Ihsan

    thanks for sharing such a nice article..
    i want to know how we can use php and html both in short code… waiting for good response thanks…

  18. Melissa Lowe

    I installed a Mailchimp for WordPress shortcode ..pasted it at the end of the text version of my document/article & no form was created & this is what it said…..MailChimp for WordPress error: There is no form with ID 0, perhaps it was deleted?

  19. Ashkan

    What for $atts in that function ?

  20. Helena

    Hi,
    I have a widget by the homepage sidebar from a multisite installation and want to have 1 widget (only one) from this sidebar working at the subsites.
    It is a text widget with a picture, this picture links to an online ebook.

    Do you think I can use this to have it done?

    Many thanks!

  21. Vinayak Ganiger

    The wp form shortcode is not working in pages but it works fine in posts. My website is vinstechs.com. In my website page named Projects is their, in that the shortcode is not working.

    What’s the solution for this, please reply with solution.

  22. Meryl

    I have a slightly more complex question.
    I’m using a theme with a theme options panel.
    I want to use a shortcode inside one of those options.
    However the output is just the [shortcode] text. Is there specific syntax I can use or does it differ from theme to theme? It’s taking forever to get answers from the theme dev.

  23. Mayank Jain

    Perfect beginner explanation!

  24. Vikash Ahlawat

    Very helpful post to create our own plugin.

  25. hirak das

    Hi i am having a problem with [login_widget] shortcode.when i inserted this code to any page/post on wordpress i only get the text but not the login form…i am using login widget with shortcode plugin…please help…

  26. Armen

    This doesn’t work if you’re trying to place another shortcode within the shortcode you’re creating.

    Say I had a shortcode like [jpshare] and I wanted to place it along with other stuff into another shortcode function like in this article to add to the posts, how would you do that?

  27. Mike

    No mention in the article WHERE to add the shortcode. Back to Google for a better tutorial.

    • Drew

      It clearly stated the code goes into ”functions.php”. If you’re not sure how to use the shortcode, it goes anything you add text.

  28. Ihatewordpress

    Hello,
    As you can tell from my name I’m very frustrated right now with wordpress.
    >>This last part is simple, just add the [adsense] shortcode in the HTML or Visual views of the Post or Page content editor.<<
    Not even a tiny clue how to do that – would you be willing to expand on this? Thank you

    • WPBeginner Support

      WordPress uses shortcodes to add functionality into posts and pages. Like in this tutorial if you wanted to display advertisement code, then you will create a shortcode for it. Once you have created a shortcode you can use it in your posts and pages. Create a new post or edit an existing one and add your shortcode with square brackets in the post content area, like [adsense].

      Administratör

      • Brock

        I installed Popup manager plugin for newsletter subscribers. I got the popup to appear by following your suggestion of putting the shortcode in a comment on my main page. This works but only if a person expands my first comment to read the entire thing. Where/how do I paste the shortcode to get the popup to appear when someone visits my page without requiring them to do anything else? I’m trying to find something in the template customization options but nothing is standing out.

  29. Patty

    Please help me understand if this is using a shortcode plugin properly. I need to display the date of the last update to a post or page to stop Google structured errors. I am using default 2014 only with plugins. I found a shortcode plugin named ”Last Updated Shortcode” that seems to do what I need. I am wondering if this is what I do.

    I would install the plugin, and then activate the plugin. Then on the page/post I would Edit page/post, and at the bottom of the post (or anywhere else if I prefer) add the shortcode. So I would literally type [lastupdated] The last updated date should then appear, correct???

    And hopefully, Google will be happy and stop emailing notices of structured errors.

  30. Larry Leek

    I’m guessing using the short codes for things like countdown timers is is only for wordpress.org or self hosted wp users correct?

  31. Anibal

    Hi I’m having trouble with the short code [tpe mylang lang=’es, en’] I know WP has recently changed this shortcode replacing the old [tp mylang=”yes” lang=”es, en” ] for the new one, but I’ve done the replacement and I still get to a 404 Nothing found error page, whenever I click on a link with this code. Any Ideas?

    • WPBeginner Support

      You are probably using Transposh plugin. Please contact the plugin support, they would be able to help you better.

      Administratör

  32. Akshat Verma

    can you recommend any good shortcode plugin for wordpress 4.2

  33. Steve

    I am having trouble figuring out how to add code comments to a page with just shortcode in it. I’ve tried HTML & PHP comment tags and when added the shortcode doesn’t work anymore. The reason I would like to comment the code is that I would like to document information about the shortcode in the page I call it from ( I may not be the site admin forever).

    • WPBeginner Support

      WordPress will strip out PHP or HTML comments in post editor. If you were using Edit Flow, then you could leave a note below the post. Right now you can switch to Text editor and leave HTML comment, but as soon as some user views the post in visual editor it will be stripped out again.

      Administratör

      • Steve

        It strips out the comments AND puts in a blank line for each comment. I put the comments below the shortcode and that works fine.
        Thanks for helping me understand what was going on.

  34. Michael

    When I add shortcode to posts, whether it be in the middle of an article or at the end, the actual element always appears at the top of the post, any idea why?

    • Malte

      Same here! How to fix that?!

      • Malte

        Okay… Use return instead of echo and everything is k!

        • James Newman

          @MALTE – I have the same issue. Can you clarify which file needs to be edited? I looked at the .php files for the plugin and could not find any echo statements to replace.

          Thanks!

  35. WPBeginner Staff

    Simply copy [rx_aeolus_three_cols] and paste it in a WordPress page. Save your page and then preview it. However, you will first have to create your portfolio in the plugin. Otherwise you will not see anything, because there is nothing for the plugin to display.

  36. Usha

    I have downloaded a plug-in ’Aeolus portfolio’ for the WordPress 3.9.2 running Twenty Eleven theme. I have been given the following shortcodes in the plug-in setting:

    [rx_aeolus_three_cols]-Displays all portfolio as three columns.

    [rx_aeolus_two_cols]-Displays all portfolio as two columns.

    [rx_aeolus_one_col]-Displays all portfolio as one column.

    Can anyone help as to how these short code can be incorporated in a page. I am new to WP plugins and badly need help.

    Thanks
    Usha

  37. Dan

    Thanks! This thread helped me a lot.

    Just in case someone else lands in here and need to use a more complex HTML/PHP code structure inside a shortcode, this is an example using some aditional options from the WordPress Shortcodes API documentation:

    Place this (and modify as needed) inside your functions.php:

    http://pastie.org/9454401

    Then you just use this shortcode inside your WordPress content :)

    [mycustomshortcode]

    Greetings!

    • Rob

      You’re the man! This is exactly what I needed. Thank you.

  38. Aymen Benzarti

    HI
    I’m beginner and this is my first time with wordpress
    so the first question when i tried this tutorial is in which file i have to write this code ?

  39. Nidesh

    Hi,

    Could you please tell me whether i have to put short codes to a particular page if i want any particular plugin to be displayed in that particular page.

    E.g. I’ve installed Collabpress plugin. And i don’t see it’s UI in the front end of my site. So do i have to insert any shortcode to a page for it to be displayed?

  40. Christina

    I would like to add the subscribe shortcode to my side menu. How do I do this?

  41. Amber T

    I am just a little confused… where am I embedding this shortcode.

    I have a columns plugin that provided the shortcode with a click of a buton, not sure if I have to take the code and embed it in my html.

    please help.

    thanks in advance!

    • WPBeginner Support

      just put the shortcode in your post content. Click on the preview button to see how it looks before publishing your post.

      Administratör

  42. Carol Manser

    Really? Easy? Simple? This website is great but it says it is for beginners. I’ve been using Wordpress for 2 years and yet I did not understand it at all. It’s quite annoying the way geeks always bang on about how easy something is and then write something totally incomprehensible to ordinary humans – just like every Math teacher I ever had.

    OK, write an article that can only be understood by geeks – fine, but please don’t keep telling me how easy it is

    output? string? content editor – where is it? define a function? I wish you would because I don’t know what it is.

    ”This function is pretty straightforward – it just returns my Google Adsense code as a string” –
    a string of what? etc etc. Just saying….

    • WPBeginner Support

      We totally agree with you that sometimes when writing we may feel that we have explained everything clearly for beginners, but a beginner level user may still not be able to understand it. This is why we have comments and we will be happy to explain it to you more :)

      A shortcode is a short+code. WordPress allows you to generate shortcodes for your programing code blocks called functions. Since a user can not write programming code in the Post Editor when writing a new post. The shortcodes provide users a way to add those programming codes into a post without writing the full code in post editor.

      When WordPress finds a shortcode in a post like this:

      [my_shortcode]

      It then executes the programming code associated with that particular shortcode.

      The example given in the article above, creates a function get_adsense. When this function is executed it outputs the adsense code. We hope this explains it for you. Let us know if you have any more questions.

      Administratör

    • Stacy

      Or the instructions are 3 lines and your wondering where are the rest of the instructions????

    • Przemek

      Totally, agree. I struggled to understand most of it, too.

  43. Alan Murray

    Can I use a shortcode on a Standalone HTML page to link to a page on my blog?

    If so how do I embed it? Does the file need to be a PHP file?

    I can’t seem to find anywhere on the net providing information on using sortcode outside Wordpress pages or posts.

    • WPBeginner Support

      Alan, shortcodes are a WordPress feature the page should be a WordPress page in order to execute the shortcode.

      Administratör

  44. DavidA

    Do you know, how to add a shortcode on a website from an other website WordPress? (multisite)
    Thx :)

    • WPBeginner Support

      yes by creating a network wide plugin all blogs on the multisite can share the shortcode.

      Administratör

  45. Lucy

    Very good one!

  46. John Rose

    Clear and concise. Thank you so much. – John

  47. Luke Ward

    Hello, thank you for this, it’s helped a lot.

    However I would like to know how to add more than one adsense in as a shortcode.
    eg [adsense1] – displays one advert [adsense2] displays a different advert.

    Thanks!

    • Editorial Staff

      Follow the same process. Change the word adsense with adsense1.

      Administratör

      • Luke Ward

        Thank you, sorry for the noob question!

        Also I have another problem now, I’m using this code to add adsense which works with responsive designs using javascript. You can see the code I’m using in the link below…

        http://www.labnol.org/?p=25252

        When this is added in after reuturn’ – nothing is displayed.

        Hope you can help with this problem as I cannot seem to find out how anywhere.
        Thanks

  48. Paul

    Just came across this as I’m looking to add my own shortcodes, I can understand the function part of it, but which document do you include the ”hook up”

    ”add_shortcode(’adsense’, ’get_adsense’); line”

    that would be helpful to me

    Thanks

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.