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

Guide för Beginnare om hur du lägger till Twitter Cards i WordPress

Genom att förbättra din WordPress site med Twitter Cards kan du avsevärt förbättra din närvaro i sociala medier och engagemanget hos användarna. Twitter Cards tillhandahåller images och descriptions som visas på X (tidigare Twitter) när någon delar ditt content.

På WPBeginner använder vi den här funktionen för att kontrollera utseendet på våra tweets och öka interaktionen med användarna. Att använda Twitter Cards (eller X Cards) ser också till att vi får kredit för vårt content.

I den här artikeln visar vi dig hur du addar Twitter Cards i WordPress, så att your tweets sticker ut.

Beginners Guide on How to Add Twitter Cards in WordPress

Varför använda Twitter Cards i WordPress?

Twitter Cards allow you to add a title, summary, image, and video or audio file to your tweet. På så sätt är det mer troligt att du får fler clicks och retweets.

Du kan se ett live-exempel genom att gå till vår WPBeginner page på X.

twitter card example

Den största fördelen med att ha Twitter Cards är att de ökar antalet personer som följer dina X-konton genom tillskrivning av content. Ofta tweetar folk dina links utan att ge dig rätt kredit.

Säg till exempel att @syedbalkhi retweetar ett post från @wpbeginner utan attribution, och andra retweetar @syedbalkhi. Då är användare som gillar dessa retweets mer benägna att följa @syedbalkhi än @wpbeginner.

Ofta gör content curates detta för att hålla tweetlängderna korta och säkerställa retweets av sina egna tweets.

Med Twitter Cards är detta problem löst eftersom du får kredit till din WordPress website från varje tweet som nämner din artikel.

Nu när du har lärt känna fördelarna med Twitter Cards ska vi ta en titt på hur du implementerar dem i WordPress. Vi kommer att täcka två metoder och visa dig hur du testar och bekräftar dina Twitter Cards:

Metod 1: Använda AIOSEO Plugin för att lägga till Twitter Cards (rekommenderas)

Det enklaste sättet att add to Twitter Cards till din website är att använda All in One SEO (AIOSEO) plugin för WordPress. Det är det bästa pluginet för sökmotorsoptimering för WordPress och används av över 3 miljoner websites.

Först måste du installera och aktivera pluginet AIOSEO. För mer details, följ vår Step-by-Step tutorial om hur du installerar ett WordPress plugin.

Du kan använda den gratis versionen av AIOSEO eftersom den erbjuder en utvald funktion för att ställa in Twitter Cards på din WordPress website.

När pluginet är aktivt går du till ditt WordPress admin area och navigerar till All in One SEO ” Social Networks. Klicka sedan på tabben ”X (Twitter)” och se till att alternativet ”Aktivera X-kort” är aktiverat.

AIOSEO Enable X Card Option

När du har aktiverat Twitter Cards kan du ändra deras appearance med hjälp av olika inställningar.

AIOSEO låter dig välja standardkorttyp för ditt content. Pluginet kommer att ställa in ”Sammanfattning” som standardkorttyp, som visar titeln, sammanfattningen och thumbnail-bilden för ditt innehåll.

Men du kan ändra det till ”Summary with Large Image” från rullgardinsmenyn, och Twitter kommer att visa din tweet med en stor image.

AIOSEO Default X Card Type

Efter det måste du välja Standard Post Image Source. Det är den image du vill visa på dina Twitter Cards.

Det finns olika alternativ att välja mellan med hjälp av rullgardinsmenyn. You can for instance upload or select a standard image that will appear in the X (Twitter) Card or select the featured image, attached image, the first image in the content, and more.

select default post image source

Next, add to a Standard Post X Image, which will be used as a backup in case your content does not have an image.

Till exempel, om din bildkälla för inlägg är en featured image, men inlägget saknar en featured image, kommer X att använda standardbilden istället.

upload default post twitter image

Notis: AIOSEO erbjuder fler alternativ för att visa ytterligare data som post författare och den tid det skulle ta att läsa en artikel.

Det finns också ett alternativ för att ställa in standardkällan för Term Image Source, men du behöver AIOSEO Pro eller en högre licens för att använda den här funktionen.

Nu, om du rullar ner, kommer du att se inställningarna för home page för Twitter. Tillägget kommer att visa en preview av hur din home page kommer att se ut på ett Twitter Card.

home page settings

Under denna section kan you ändra Card Type och add to en Home Page Image.

Detta liknar de steg vi visade tidigare, men skillnaden är att dessa inställningar gäller för din home page.

home page card type and image

Därefter anger du en Home Page Rubrik och Description som kommer att visas på Twitter Card.

När detta är gjort, clickar du på knappen ”Save Changes”.

home page title and description

Notis: AIOSEO låter dig också ändra inställningarna för X (Twitter) Card för enskilda poster och pages.

För att göra det, edit någon blogginlägg eller page och rulla sedan ner till AIOSEO Settings i content editor. Klicka nu på tabben ”Social” och select ”X (Twitter)”.

AIOSEO X (Twitter) Settings for a Post

Tillägget visar en preview av ditt posts X Card och ger dig alternativet att använda data från Facebook tabs. Det låter dig också editera X-titeln och description.

Du kan skriva en new titel och description eller använda smarta taggar. Om du till exempel använder taggen ”+ Post Rubrik” ovanför fältet Twitter Rubrik, kommer AIOSEO automatiskt att använda titeln på ditt post i Twitter Card.

twitter card settings for posts and pages

Därefter rullar du ner och väljer Image Source för ditt Twitter Card. Använd rullgardinsmenyn för att välja den image du vill visa för ditt inlägg, gillar en utvald image, attachment image, första image i content, och så vidare.

Slutligen kan du välja Twitter Card Type från rullgardinsmenyn. Som standard kommer AIOSEO att ställa in den på ”Summary”, men du kan ändra den till ”Summary with Large Image”.

image source and card type

Därefter uppdaterar eller publicerar du ditt blogginlägg. Du har nu utan problem addat Twitter Cards till din WordPress website.

Metod 2: Lägga till Twitter Cards i WordPress (kodmetod)

Denna metod kräver att kod läggs till i filerna för ditt tema eller barntema. Öppna bara header.php-filen eller använd det gratis pluginet WPCode för att add to denna custom-kod precis före taggen </head>:

<?php
#twitter cards hack
if(is_single() || is_page()) {
  $twitter_url    = get_permalink();
 $twitter_title  = get_the_title();
 $twitter_desc   = get_the_excerpt();
   $twitter_thumbs = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), full );
    $twitter_thumb  = $twitter_thumbs[0];
      if(!$twitter_thumb) {
      $twitter_thumb = 'http://www.gravatar.com/avatar/8eb9ee80d39f13cbbad56da88ef3a6ee?rating=PG&size=75';
    }
  $twitter_name   = str_replace('@', '', get_the_author_meta('twitter'));
?>
<meta name="twitter:card" value="summary" />
<meta name="twitter:url" value="<?php echo $twitter_url; ?>" />
<meta name="twitter:title" value="<?php echo $twitter_title; ?>" />
<meta name="twitter:description" value="<?php echo $twitter_desc; ?>" />
<meta name="twitter:image" value="<?php echo $twitter_thumb; ?>" />
<meta name="twitter:site" value="@libdemvoice" />
<?
  if($twitter_name) {
?>
<meta name="twitter:creator" value="@<?php echo $twitter_name; ?>" />
<?
  }
}
?>

Du kan ändra värdet för ”twitter:card” på rad 14 till ”summary_large_image” om du vill visa ett summary-kort med en stor image.

Om du inte vet hur man arbetar med PHP eller om du runar på issues med metod 2, vänligen använd metod 1.

Testa och bekräfta dina Twitter Cards

Innan links från din WordPress site börjar visa Twitter Cards, måste du först kontrollera det i Twitter Card Validator.

Bara heada över till Card Validator page på Twitter utvecklarnas website. Enter URL:en till ett post från din WordPress site och click på knappen ”Preview card”.

Twitter Card Validator

Card Validator visar inte längre en preview av tweeten, men den visar en logging om Twitter-kortet hämtar utan problem eller ej.

Update: Tidigare var du tvungen att ansöka om att få delta i Twitter Cards. Twitter har dock implementerat ett system som automatiskt whitelistar domäner när du testar dem med giltigen eller bara delar en URL på Twitter.

Expertguider om hur du använder Twitter med WordPress

Nu när du vet hur du addar Twitter Cards till WordPress kanske du gillar att se några andra guider relaterade till att använda Twitter med WordPress.

Vi hoppas att den här artikeln hjälpte dig att add to Twitter Cards till WordPress. Du kanske också vill se vår guide om hur du skapar en landing page med WordPress och vårt expertval av de WordPress tillägg som du måste ha för att utveckla din website.

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

88 kommentarerLämna ett svar

  1. Syed Balkhi

    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. Nick Farrell

    You can also just throw your meta tags right into the body of your post. Not the ideal way, since this creates empty white space where your tags are, but it’s a good workaround for those having trouble.

  3. Laurel

    If the php code above seems to break your site, it could be that your server doesn’t use php short tags (using “<?" as an opening tag instead of "<?php"). Try this version instead:

  4. Prabs

    Hi thanks for the informative post. However I did all this and when testing my site through the card validator, was told it was unable to generate image because my site isn’t whitelisted! Any idea what I can do?

  5. Sarah

    Hi,

    I realise this is an old post,

    IF you HARDCODE into your header.php; make sure you change the values line 10 and 19 as these point to the contributors account so be sure to change them to yours.

    just sayin … ;-)

  6. Jahmya

    Hi,
    I have done all the steps when I try to validate with twitter it tells me my text description meta tag is missing. I don’t know anything about code so I used the first method. Any help?

  7. sonam

    is it free ?

  8. Tyler

    Finally a helpful tutorial! You would think that Twitter would make it a little simpler to do this. Thank you so much for your help on this!

  9. Michael

    Is there a way to automatically notify the twitter validator when a post/page is updated?

    I have a site that gets content published automatically from a source without a featured image so once I manually add the image I also have to manually validate the post/page again to get the cards to show on twitter.

    Was hoping there could be some way to automatically ping the twitter validator when a page/post is updated.

  10. Azita

    I don’t know why the code above cut off.
    Here is the code am using:
    ID), full );
    $twitter_thumb = $twitter_thumbs[0];
    if(!$twitter_thumb) {
    $twitter_thumb = ’url of imag’;
    }
    $twitter_name = str_replace(’@’, ”, get_the_author_meta(’twitter’));
    ?>
    <meta name="twitter:title" content="” />
    <meta name="twitter:description" contente="” />
    <meta name="twitter:image" content="” />

    • Azita

      Thank you so much. I figured out. No worries. Please disregard this comment.
      Thank yu again.

  11. Adrian Robertson

    Another awesome post … great stuff!

    For anyone having issues with the image being display (I have Summary selected as my Twitter Card option) just make sure you are using a featured image, as this is where it pulls from.

    Without this specified, what I saw was my site logo (which was way too big for the Summary image)

  12. Nefeli D

    Can’t thank you enough ! :)

  13. Cheo

    Hi, i’ve made all steps and got the twitter card ok, but the preview image is not loading! what should i do?

    • WPBeginner Support

      If you are using code method, then please try using the plugin method. If you are already using the plugin method, then try repeating all the steps carefully.

      Administratör

  14. shamsher

    i have a question that when where to upload it on all pages and post or on home page only.

    bcoz when i share any link of my blog on twitter after adding this in header every time same image appears.

    • Adrian Robertson

      Is it your site logo that appears?
      Just check that you have a feature image set against your post, and it should pull from there

  15. Roger Dunkelbarger

    Found this article and followed the steps to set up Twitter Cards since we already had Yoast. We want to use the video Player Card but that doesn’t appear to be an option. Do we need to use a different plug in, or is that option available?

  16. Amanda

    I”m using twitter cards through my Yoast SEO, however when I post I have a link and a view summary button that people have to click to see my pictures. I want the pictures to be auto populated without the need for a click. How do I make that happen?

    Here is my twitter account so you can see my tweets for an example

  17. Graham

    All going well with the inclusion of twitter cards. I would like to make the image that displays on twitter link able or to a link underneath to take it to a third part site any ideas?
    Oh and by the way I would like to thank you guys for realizing that not everyone degree is in computer science and won at MIT !!

  18. Tina Marie Ernspiker

    Thank you very much! My blog is white-listed now, with Twitter Cards :-) Whoot, whoot!

  19. Jas

    Hi,

    Thanks for your tutorial. I have tried with above code. But can you please explain how to make Twitter card working for multiple accounts.

    I have ten different twitter pages where same post will go out as Twitter card.

    So do I need to repeat this below line 10 times with different names:

    …..

    ….
    ….

    Please suggest?

    Thanks!

    • jas

      code doesn’t shows in my previous comment I mean to say meta tag with Twitter site name need to get repeated with different names?

      <meta name="twitter:creator" value="@” />

  20. Edna

    This was super helpful, thanks!

    One quick thing, I noticed the validation link is no longer working. I think this is the Card Validator link now (got it from the twitter blog, seemed to work fine for me):

  21. Maha

    How to request to twitter for approvel my site ..please help me i tried twitter card ,the preview tool say your card is whitelisted ..

  22. riad

    hi i love your site very nice i want to asking you how to change the language of wordpress from franch to english or arabic

    • WPBeginner Support

      You can change the language from Settings > General page in WordPress admin area.

      Administratör

  23. Paul Middlebrooks

    The Yoast solution did not work for me. I followed the instructions (3 times to make sure), and the Card Validator sees my metadata but tells me I have no card.
    Also, neither the Preview Tool nor the ”FIll out This Form” links worked:
    https://dev.twitter.com/docs/cards/preview

    Maybe this solution is already history?

  24. samiOOTB

    I had done this and Twitter cards were working perfectly for months. Suddenly the past few days they’ve stopped working. What can I do?

  25. Megan Kubasch

    So I have installed WP SEO by Yoast, and I have followed all of the instructions up to the point where I insert the Card URL on the Preview page for the Card Validator on Twitter. What URL am I supposed to Insert? I have used my URL for my blog, but it comes up with an error, saying No Card Found (Card Error). Any help you can provide would be greatly appreciated.

  26. Eric Yoffie

    My twitter card has been approved, but I don’t know how to make it work. Am I supposed to fill out a form? I am a WordPress user.

  27. Lauren Riley

    This is really useful thank you.

    One thing, we have enabled this using the WordPress Yoast SEO Plug-in and set up a Twitter card manually entering all of the information on the card validator for one blog post.

    This worked, however when I tweet a link to my other blog posts it doesn’t pull through the Twitter card. Do you have to set up the Twitter cards for each blog post or should it do it automatically for each blog post?

  28. Manuel Echeverry

    graciass!!! thank you! finally I managed to submit my request to twitter, hopefully i will get my card approved

  29. Ruth

    Oh, and ps
    Do we have to approve each post, or will that be automatic after our first post was approved… Again, thank you

  30. Ruth

    Thanks, it works great, except for one thing: I can’t get an image to be included. How would I do that,

  31. Karan Singh

    when i install this plugin then it is asking for “You’ve just installed WordPress SEO by Yoast. Please helps us improve it by allowing us to gather anonymous usage stats so we know which configurations, plugins and themes to test with” Allow Tracking or not, what should i do,
    Allow tracking or not.

  32. Sri Ganesh.M

    The codings are not working for animhut blog. Showing error ! Invalid card type

  33. Kevin

    Hello there. Great guide, thanks!

    I’m currently stuck trying to validate twitter:creator. When I look at the source for one of my posts, I don’t see the twitter:creator meta tag at all. Would you mind, pointing me in the right direction? I’m hard-coding it.

  34. Gareth

    Great post – i was struggling to set up twitter cards using a wordpress plug in without realising that Yoast had it in-built!

    All set up and awaiting approval – thanks guys

  35. Jason Acidre

    Useful post! Been planning to add Twitter cards on my blog for ages now, and just had the time to tweak it earlier, found this guide very helpful, so thanks.

  36. Reap3RGHS

    Hello,
    I having a simple problem. I going to add my twitter username to my profile settings. I just add Reap3R_GHS and turn it into http://reap3r_ghs. What can I do?

    • Editorial Staff

      That’s weird. Did you post it in the support forum for Yoast to see?

      Administratör

      • Reap3RGHS

        Isn’t in Yoast settings but in profile settings…

  37. Julien Maury

    Hi,

    It’s great but because we call the excerpt outside the loop (header), people could get bad surprises for their description.

    So here is a good snippet from uplifted.net that fixes the problem :

    function get_excerpt_by_id($post_id){
    $the_post = get_post($post_id); //Gets post ID
    $the_excerpt = $the_post->post_content; //Gets post_content to be used as a basis for the excerpt
    $excerpt_length = 35; //Sets excerpt length by word count
    $the_excerpt = strip_tags(strip_shortcodes($the_excerpt)); //Strips tags and images
    $words = explode(’ ’, $the_excerpt, $excerpt_length + 1);
    if(count($words) > $excerpt_length) :
    array_pop($words);
    array_push($words, ’…’);
    $the_excerpt = implode(’ ’, $words);
    endif;
    $the_excerpt = ” . $the_excerpt . ”;
    return $the_excerpt;
    }

    Then you might replace get_the_excerpt() with this :
    get_excerpt_by_id($post_id)

    Thanks. :)

    • Julien Maury

      Sorry that wasn’t exactly that :

      Call the function this way : get_excerpt_by_id($post->ID) otherwise you’ll get notice !
      $post_id is undefined.

      Plus get_the_excerpt() is deprecated.

      You can also add an esc_attr() on $the_excerpt to avoid broken meta if the excerpt has quotes

      Thanks !

    • Main Uddin

      There is no needs to use any code , simply use WordPress SEO by Yoast as Syed Balkhi has said which is the best for Twitter card

      • Julien Maury

        Hi,
        There’s no need to use any code. But still my plugin allows you to choose which type of card you want to use on each post. Moreover you can change meta creator (guest blogging) per each post too. I think it’s worthy :)

        • Roy McKenzie

          Totally Worthy!

  38. Manuel Garcia

    When I preview my twitter card, the error says:
    ”Internal Error. Most likely an fetcher error.”
    What to do?

  39. Sai Liou

    Thank you for the article! I went with method #1. In the twitter preview, I’m only seeing the summary of the post and not the image. I’ve updated the robot.txt file to allow twitterbot. However, it’s still not showing any image in the preview. Any thoughts on this? Thank you in advance.

    • Editorial Staff

      Look in your view:source to see if you have the image tags. The image is usually pulled from your featured image.

      Administratör

  40. Mattia Frigeri

    Good article. I activated the summary card…

    Anyway: how do you change the anchor text name of the website in the attribution below?
    For instance yours is ”WordPress Beginner”, other sites use ”example.com”. In my case it uses my name. How do you manage it? I’d like to show a piede of my URL like ”example.com”

  41. David Benson

    Just wanted to let you know that this post saved me HEAPS of time trying to get this to work. Clear, clean and to the point walkthrough. It’s very much appreciated.

    A followup question. I added all the steps to my blog, TheSocialChic.com, but I’m curious as to how much time it usually takes for them to turnaround an approval process. Will I get an email or anything when I (or if) I am approved for Twitter cards? No worries if you don’t know, but I greatly appreciate any guidance on this topic.

    Thanks again for such a helpful post. Keep up the good work and I will be definitely staying tuned to all future posts.

    • Editorial Staff

      Approval time varies. In our experience, twitter cards were enabled on our account before we received an email from twitter. But yes, we did receive an email from twitter.

      Administratör

      • David Benson

        Thanks for letting me know. Very much appreciated. Keep up the great work with this site. I will be staying tuned.

  42. Bridie Jenner

    I now have this on my site, and very exciting as the first blog post I tried worked – fantastic!

    But I’ve tried it with a few others and it’s not showing the summary… any ideas?

    • Editorial Staff

      Did twitter approve your site yet? Remember, they have to approve the site first.

      Administratör

  43. Bridie Jenner

    These are great! Just applied to Twitter for mine and will be sharing this. Thanks.

  44. John John

    Awesome article, thank you for all these infos.

  45. Parvez Ansari

    I got ”Summary Card” working for me by following method 2 for my website which is built usng wordpress. I inserted the code to generate meta data in the single-page wordpress template.

    I want to know ”how” and ”when” to use ”Photo Card”

    • Editorial Staff

      You would use photocards on photo specific pages. For example if you have a photo blog, then it makes more sense for you to use a photocard.

      Administratör

  46. Urban Renstrom

    Thank for the twitter card tip.

    under my profile my twitter handle was missing, doh…

  47. Brent Pittman

    Wow! Thanks for keeping us updated with the latests. It seems like this will save a lot of time and we won’t have to attribute the source since it is done automatically.

  48. Lisander

    Thanks for the tutorial.. I was wondering what that twitter card on yoast’s plugin was.
    But now I know, I hope I get accepted.

  49. Rakesh M. Pawar

    Hello, thanks for article, we’ll try this code to implement Twitter Cards.
    I’ve one more question (I know this question is not related to this article): How to get such effects like in your post, when we hover mouse over twitter handle it shows popup with follow button, please tell us how to implement that? Thanks in advance.

  50. Nino Blasco

    Always good articles, congratulations.
    I’ll try just the code.
    Thank you.

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.