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 stylar du varje WordPress-post på olika sätt

Vill du utforma varje WordPress post på din website på olika sätt?

Du kanske har stött på några webbplatser som markerar (fast)klistrade inlägg med en custom bakgrund eller stylar varje kategori inlägg med ett unikt utseende. Du kan också göra detta för att återspegla olika content typer och skapa en visuellt tilltalande upplevelse för användarna.

I den här artikeln kommer vi att visa you hur du enkelt kan utforma varje WordPress post på olika sätt.

Style Each WordPress Post Differently

Note: Denna tutorial kräver att du addar custom CSS i WordPress. You will also need to be able to use the Inspect tool and have some basic CSS knowledge, so it may not be suitable for complete beginners.

Pro och Contra med att Styla varje WordPress post på olika sätt

Om du har en WordPress-blogg kan styling av varje post på olika sätt skapa en unik visuell upplevelse där olika färger associeras med olika kategorier eller typer av content.

For instance, you might use a different bakgrundsfärg for all the listicles, blogginlägg, and how-to tutorials on your website. Detta kan fånga användarnas uppmärksamhet omedelbart och öka engagemanget.

Tänk på att detta också kan ha några stora nackdelar. Till exempel måste du regelbundet underhålla designen av varje WordPress post, vilket kan vara tidskrävande.

Dessutom kan det ge en inkonsekvent upplevelse för användarna och hjälper inte till med din varumärkesidentitet. Detta beror på att du måste använda samma färger på hela din website för att etablera ditt företags image.

Om du är en Beginner, kan det också vara svårt att lägga till customize CSS för att styla varje post. Med detta sagt, låt oss se hur du enkelt kan utforma varje WordPress post på olika sätt.

Så här stylar du enskilda posts i WordPress

WordPress lägger till standard CSS-klasser till olika element på din website. Themes använder en WordPress core-funktion som heter post_class() för att berätta för WordPress var de ska add to dessa standard CSS-klasser för posts.

Om du besöker din website och använder Inspect-verktyget i din webbläsare kommer du att kunna se de klasser som lagts till för varje post.

Use the Inspect tool to view the CSS classes

Följarna är de CSS-klasser som läggs till som standard baserat på vilken page en användare viewar:

  • .post-id
  • .post
  • .attachment
  • .sticky
  • .hentry (sidor i mikroformatet hAtom)
  • .category-ID
  • .kategorinamn
  • .tag-name
  • .format-{format-namn}
  • .type-{namn på post type}
  • .har-inläggsminiatyr

Ett exempel på utdata skulle kunna se ut så här:

<article id="post-412" class="post-412 post type-post status-publish format-standard hentry category-news">

Du kan utforma varje WordPress post på olika sätt med hjälp av dessa respektive CSS-klasser eller ID:n. För att göra detta måste du först hitta post ID:n för en enskild post.

För att göra det måste du besöka Posts ” All Posts page från WordPress dashboard och hovera musen över ett post.

En URL för edit av post kommer nu att visas längst ner till vänster på din vy. Här kan du hitta postens ID:n genom att titta på siffran mellan ”post=” och ”&action”.

I exemplet under är ID:n för posten 25.

När du har gjort det måste du add to CSS-klassen tillsammans med den anpassade koden till dina temafiler eller i temats customize. Det kan dock vara riskabelt och förstöra din site med bara ett error.

Det är därför vi rekommenderar att du använder WPCode istället. Det är det bästa WordPress code snippets plugin och det säkraste sättet att add custom code till din site.

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

Efter aktivering, besök Code Snippets ” + Add Snippet page från WordPress dashboard. Här klickar du på knappen ”Use Snippet” under alternativet ”Add Your Custom Code (New Snippet)”.

addnewsnippet

Detta tar dig till sidan ”Create Custom Snippet”, där du kan börja med att lägga till ett namn för ditt code snippet. Därefter väljer du ’CSS Snippet’ som code type från dropdown-menyn till höger.

Sedan måste du add to din enskilda posts CSS-klass och ID:n i ”Code Preview” boxen gillar detta:

.post-13 { }

Efter det kan du add to alla typer av custom CSS-kod mellan parenteserna för att styla din post.

Add the individual post ID in the Code Preview box

Om du till exempel vill ändra bakgrundsfärgen för ett enskilt post kan du add to följande custom CSS-kod. Tänk på att du måste ersätta post ID i den här koden med ditt eget ID. Där detta är .post-13, kan din vara .post-23873.

You can also change the hex code for the backgroundsfärg to any color of your choice:

.post-13 {
background-color: #FF0303;
color:#FFFFFF;
}

Därefter togglar du omkopplaren ”Inaktiverad” högst upp till ”Aktiv” och klickar på knappen ”Save Snippet” för att lagra your settings.

Den anpassade CSS-koden kommer nu automatiskt att köras på din enskilda post vid aktivering av snippet.

Activate the CSS code snippet for the individual post

Gå vidare och besök ditt WordPress blogginlägg för att se ändringarna i realtid.

Du kan också add to andra custom CSS code snippets i ”Code Preview” boxen för att ändra textvalsfärg, textfärg, färg på interna länkar och mycket mer.

Background color preview for an individual post

För mer information, se vår guide för nybörjare om hur du customize färger i WordPress.

Hur man stylar poster i en specifik kategori

Om du vill styla alla de posts som tillhör en viss kategori kan du också göra det med WPCode.

Du måste besöka Code Snippets ” + Add Snippet page och välja alternativet ’Add Your Custom Code (New Snippet)’.

Lägg sedan till ett kod snippet namn på den nya sidan och välj ”CSS Snippet” som kod typ. Därefter skriver du en specifik kategoris CSS-klass i boxen för förhandsgranskning av kod så här, med kategorins permalänk slug efter bindestrecket:

.category-books { }

När du har gjort det kan du lägga till valfritt custom CSS snippet i boxen för att tillämpa det på alla posts i olika kategorier.

Add the category CSS class and name in the code preview box

Till exempel, om du vill ändra fontstorlek och stil för alla poster i en viss kategori, kan du använda följande code snippet. Kom bara ihåg att ersätta kategorinamnet enligt din website.

category-books {
    font-size: 18px;
    font-style: italic;
}

Därefter toggle ”Inactive” till ”Active” högst upp.

Gå sedan vidare och klicka på knappen ”Save Snippet” för att lagra dina settings.

Preview of all the styled posts in a specific category

Du kan nu besöka alla posts i en viss kategori för att se de ändringar som har tillämpats med CSS-kod.

Så här gillade vi det på vår demo site.

Preview of all the styled posts in a specific category

Hur man stylar inlägg på olika sätt baserat på författare

Standard CSS-klasserna som genereras av funktionen the_posts() inkluderar ej författarens namn som en CSS-klass.

Om du vill customize stilen för varje post baserat på författaren, måste du först lägga till författarens namn som en CSS-klass.

För att göra detta med WPCode, välj alternativet ”Add Your Custom Code (New Snippet)”.

Detta kommer att ta dig till ”Create Custom Snippet” page, där du måste add to ett namn på code snippet och select ”PHP Snippet” som code type.

Följ detta genom att add to följande custom code i ’Code Preview’ boxen och ersätt ’user_nicename’ med författarens namn.

$author = get_the_author_meta('user_nicename'); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( $author );

Slutligen toggle ”Inaktiverad” till ”Aktiv” och klicka på knappen ”Save Snippet” för att store dina settings.

Det ska se ut så här.

Add the author's name as a CSS class

Den här koden kommer nu att add to användarens nicename som en CSS-klass. Nicename är ett URL-vänligt namn som används av WordPress. Det har ej mellanslag och alla tecken är gemener, vilket gör det perfekt att använda som en CSS-klass.

Nu måste du besöka Code Snippets ” + Add Snippet page igen och välja alternativet ’Add Your Custom Code (New Snippet)’. På nästa vy lägger du till ett namn för din custom code och väljer ’CSS Snippet’ som code type från dropdown-menyn till höger.

Du kan sedan add to den specifika författarens namn i ”Code Preview” boxen gillar detta:

.sarahclare

Därefter kan du add to den custom CSS-koden för att ändra bakgrundsfärg, kantstorlek, textfärg och mer.

Add the author's name in the code preview box

Du kan använda koden under för att ändra bakgrundsfärgen på en författares posts och add to en kant på content area.

.sarahclare {
background-color:#EEE;
border:1px solid #CCC;
}

När du är klar klickar du på knappen ”Save Snippet” högst upp.

Toggle sedan omkopplaren ”Inaktiverad” till ”Aktiv”.

Activate CSS snippet to style a specific author's posts

Den customize koden kommer automatiskt att aktiveras vid aktivering.

Du kan nu besöka en viss författares post för att se ändringarna.

Preview of a specific author's styled posts

Hur man stylar inlägg baserat på popularitet med hjälp av antal kommentarer

Du kanske har sett webbplatser med widgetar för populära post, som ibland baseras på antal kommentarer. I det här exemplet visar vi you hur man stylar posts på olika sätt med hjälp av antalet kommentarer.

Först måste vi hämta antalet kommentarer och associera en klass med det.

För att få antalet kommentarer måste du add to följande kod till dina theme-filer, eller så kan du använda ett code snippets plugin som gillar WPCode.

Välj bara alternativet ”Add Your Custom Code (New Snippet)” för att starta sidan ”Create Custom Snippet” i WPCode.

Här väljer du ’PHP Snippet’ som kodtyp och sedan copy and paste följande kod i Code Preview box:

<?php 
    $postid = get_the_ID();
    $total_comment_count = wp_count_comments($postid);
        $my_comment_count = $total_comment_count->approved;
    if ($my_comment_count <10) {
        $my_comment_count = 'new';
    } elseif ($my_comment_count >= 10 && $my_comment_count <20) {
        $my_comment_count = 'emerging';
    } elseif ($my_comment_count >= 20) {
        $my_comment_count = 'popular';
    }
?>

Därefter klickar du på knappen ”Save Snippet” och toggle ”Inactive” till ”Active” för att lagra dina settings.

Den här koden kontrollerar antalet kommentarer för det post som visas och tilldelar dem ett värde baserat på antalet. Till exempel får posts med färre än 10 comments en klass som heter new, färre än 20 kallas emerging och allt över 20 comments är popular.

Add the comment count code snippet

Nu måste du add to antalet comments som en CSS-klass till funktionen post_class. För att göra detta måste du öppna sidan ”Create Custom Snippet” igen och välja alternativet ”PHP Snippet” från dropdown-menyn.

Add to sedan följande custom code i preview boxen:

<article id="post-<?php the_ID(); ?>" <?php post_class( $my_comment_count ); ?>>

Efter det klickar du på knappen ”Save Snippet”.

Du kan nu toggle omkopplaren ”Inaktiverad” till ”Aktiv”.

Add comment count as CSS class

Detta kommer att add new, emerging, och populära CSS-klasser till alla posts baserat på antalet comments som varje post har. You can now add custom CSS to style each post based on its popularity (Du kan nu lägga till customized CSS för att styla varje post baserat på dess popularitet).

Till exempel kan du använda följande kod för att add to olika kantfärger för posts baserat på antalet kommentarer som publicerats på dem.

.new {border: 1px solid #FFFF00;}
.emerging {border: 1px dashed #FF9933;}
.popular {border: 1px dashed #CC0000;}

När du är klar, glöm inte att clicka på knappen ”Save Snippet” för att store dina settings.

Style posts based on popularity

Bonus: Display a Different Sidebar for Each Post in WordPress (Visa olika sidebar för varje post i WordPress)

När du har stylat varje post på olika sätt kanske du också vill add to en unik sidebar för varje post. Detta tillåter dig att visa upp specifikt content relaterat till den artikeln som användare kan vara intresserade av.

Om du till exempel har en reseblogg och har publicerat ett blogginlägg om platser att besöka i Florida, kan du skapa ett specifikt sidebar som visar resepaket för Florida. Alternativt kan du visa ett registreringsformulär för en Floridaresa som du organiserar.

För att visa en annan sidebar för varje post kan du använda SeedProd, som är det bästa page builder plugin för WordPress.

SeedProd website

Det har ett drag-and-drop-gränssnitt, 320+ färdiga templates och integrationer med tjänster för e-postmarknadsföring, vilket gör det till ett utmärkt val.

Vid aktivering av plugin kan du välja en custom page som din landing page-design och sedan en layout med ett sidofält.

Choose a Layout with a Sidebar

Efter det kan du enkelt dra and drop block som du väljer från den vänstra Column, inklusive Contact Form, archives, giveaways, search box, comments, och mycket mer.

När du är klar klickar du bara på knapparna ”Save” och ”Publicera” i dropdown-menyn högst upp. Nu har du utan problem skapat en specifik sidebar för ett post eller en page i WordPress.

Drag the Blocks You Wish to Use Right onto the Sidebar

För detaljer, se vår tutorial om hur du visar en annan sidebar för varje post och page i WordPress.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du stylar varje WordPress post på olika sätt. You may also want to see our beginner’s guide on how to style tags in WordPress and our list of the most wanted WordPress tips, tricks, and hacks.

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

54 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. Rafael says

    Nice article. I guess I could use something like this to check the category of a post and place a custom CSS to change the style of part of the website according to the category, right?

    I’m looking to set different colors only to the background of the Title of the Post for each Category in a Blog.

    • WPBeginner Support says

      Your theme would need to add something that can be targeted by CSS, at the moment we do not have a recommended method for adding that.

      Administratör

  3. Les says

    Great article. I wanted to set the default Font size per category and followed the instruction by adding the code to the Style.css file but when I added a new post the font was the old size. See code? What am I missing?

    /* Begin Additional CSS Styles */
    .art-blockheader .t, .art-vmenublockheader .t {white-space: nowrap;}
    .desktop .art-nav-inner{width: 1200px!important;}

    .category-firstg {
    font-size: 18px;
    font-style: bold;
    }
    /* End Additional CSS Styles */

  4. William D says

    Great article, thank you very much. Could the read more button color/text color also be changed in a similar manner? Something (I probably did) has changed my buttons in a very unpleasant way and I’m having a heck of a time trying to figure out how to make them pleasant again.

    Thanks in advance for any help you might provide!

  5. Neon Emmanuel says

    Hello, if i include this in single.php it echo back the current post title, but works fine in index.php, any suggestion to this?

  6. marisa says

    This is a great article but I’m having trouble with placing
    ID, ’post-class’); ?>

    Where exactly in the loop do I put it? I am using underscore.me with foundation 5 and my new class isn’t appearing.

  7. Payal says

    Very informative, thank you. I’ve bookmarked this page.

    I also have a question: What if I wanted to style the first (latest) post differently — so that the post displayed at the top of my index page shows up differently?

  8. James says

    Hey there, I’m struggling with this atm..

    My post loop doesnt seem to have a post_class function so I cant figure out where to place the above code…

    This is the loop I use for posts, where would I place the above code? Or how could I get custom fields to work using this?

  9. Jon Fuller says

    Hello, I am quite new to making WordPress themes and I am looking for a way to display each post in a box of its own which is seperated by a margin top and bottom. Please explain how this is possible.

    Thanks

  10. Shaun says

    Curious, how could this be applied to adding a CSS class to only posts posted that have the same ”meta value” or ”meta value number”?

    Thanks for the great tutorial by the way!
    Best

    • Editorial Staff says

      We showed how to do it with custom fields, but that’s being done by key. But if you have the same key with multiple values, then you should get_post_custom_values function.

      Administratör

  11. Jim says

    I would like to do something where post one gets the class ”1”, post two gets ”2” post three gets ”3”, and then it repeats this order, so post four gets ”1” again.

    Any tips? it’s just repeating three different classes every three posts.

  12. Brit says

    What I’m trying to do specifically is just make it so when someone lands on my blog, that the thumbnail (which is just a circle with the post title) is a different color for ONLY the most recent post. I’m at a loss of how to make this happen. Everything I’ve found is category or order specific. Thoughts?

    • Editorial Staff says

      Brit, you would have to use the last method ”Super Loop”. That is probably the only way of doing it because all what you would do is on the first post, you add a unique class such as ”first-post” , and then style that using your CSS file.

      Administratör

  13. vajrasar says

    Well, that is a very good piece. I got what you said, but can you shed some light on how am gonna implement this on my Genesis driven News Child theme, as I am supposed to do all this with function.php

    I would like to style category specific posts differently. Thanks a lot for this piece. very informative.

    • Editorial Staff says

      So if you are just using the post class method, then Genesis has the field under their Layout settings for each post. You can enter a custom class and style it that way. The rest can get pretty complicated depending on all the hooks and such. We don’t necessary do genesis specific articles here.

      Administratör

  14. jim says

    What do you mean index.php in the loop. which index.php. Mine has nothing like yours. This is the 10th post I’ve read where no one has explained this basic concept properly. And what about the CSS. Last 10 posts didn’t explain that either. Internet is getting worse and worse.

    • Editorial Staff says

      Hey Jim,

      Every WordPress theme does things differently. The concept of loop is pretty well explained in the WordPress Codex. It requires a simple google search: Loop WordPress which will take you to: http://codex.wordpress.org/The_Loop

      Because every theme varies, some utilize a separate loop.php file others are child themes which don’t even have index.php files. It is really hard to explain all of those concepts. When we put tutorials in a theme category, we expect the users to have a fair knowledge of how WordPress themes work (even if you don’t know PHP).

      Administratör

  15. gashface says

    Nevermind got that working, but NOW it doesn’t style each post differently, it just styles them all according to the first post author it finds?

  16. gashface says

    Is there a way to specificy a tag like H2 is styled by author I am trying .username h2{} for example but it won’t work?

  17. gashface says

    This doesn’t show the author with me just a blank space, pasted your exact code, any ideas? posts made by admin and are private, does that make a difference?

    • wpbeginner says

      @gashface not it doesn’t make a difference whether the post is private or public… If it is returning a white page, then you are pasting the code in a wrong place.

      • gashface says

        I realised it was because I was putting the code before the call to the loop, I thought you meant before the if have posts etc.. when it needs to go after that, thanks for the heads up

  18. KimeeDoherty says

    This was a little helpful, but I am still lost :( Not sure how to include the loop file in order to override the template. You started the <div> tag but not ended them, what’s inside the div? I’m lost :(

  19. Stuart says

    Hi, thanks for the ideas – especially the super loop – pleased to have got it working on my site.

    But I wonder, complete php beginner here, so is there a way to adapt the code so each subsequent page of posts doesn’t get the styling that posts 1, 2, 3, & 4 get on the first page.

    In other words, I only want the first four posts on the first page to look any different to the rest.

    Cheers,
    Stu

  20. Michael says

    If you wanted to use this approach to separate posts visually based on their published date. How would you go about it? For example: style the 5 posts published on the 1st with a black background, and then style the posts published on the 2nd with a red background? Thanks in advance!

  21. Dale says

    I am trying to style each authors name a different colour on our wordpress website and I have followed your code as below:

    Whilst this code is kind of working on my wordpress theme it is putting end quotation marks after class-2 but before the authors name so the class is being closed without the name in it. I only found this out by putting that php inside the body where you can see the full string.

    Does anyone have any ideas why this is happening?

    • Dale says

      Sorry it stripped out the php I posted but here is the class output of styling my posts by the authors name. The author here is called admin, and as you can see the closing tag is before the author name admin.

      ”post-395 post type-post hentry category-uncategorized class-1 class-2″admin

  22. Adam W. Warner says

    Indeed a great post, hats off! However, I couldn’t help but keep thinking about when it’s time to upgrade the theme you’re making all these custom edits to. I try to use the functions file whenever possible to avoid overwrites.

    I would think it would be better to roll these loop edits into a function. I know that with Parent Themes like Thematic, Hybrid, Genesis, etc…that it’s possible (and advisable) to filter the loop and thus add these changes.

    @Ken – Maybe your plugin would negate the need for any functions altogether?

    Anyway, just my two cents and congrats Syed and the team on your continuing excellence on this site!

  23. Ken says

    Your article has giving me a few ideas on how to improve my plugin, thanks for that!

    I just wrote a plugin (Scripts n Styles) for adding CSS directly to the head element from the post/page editing screen. (Only admin users can do this though.) It’s not as robust (or rather, doesn’t address the same thing) as your solution because the CSS only appears on the single view, not in the lists (archives).

    I’m considering adding the functionality to include a class name into post_class, but via a meta box on the admin screen. Then, the admin would only have to add the css to his theme. (Or, perhaps a setting screen to facilitate this?)

    Anyway, the Super Loop seems useful for theming in general, I’ll have to include that in my next one!

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.