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 visar du senaste inlägg från en viss kategori i WordPress

Vill du visa de senaste inläggen från en viss kategori på din WordPress site?

Filtering av inlägg by category allow you to show more relevant recent posts, which can help to reduce bounce rate and increase pageviews.

I den här artikeln visar vi dig olika sätt att visa senaste inlägg från en viss kategori i WordPress.

How to Display Recent Posts From A Specific Category In WordPress

Varför filtrera posts efter Category i WordPress

Displaying recent posts allows users to discover new content as they browse through your website. Detta bidrar i hög grad till att öka trafiken på din blogg och antalet views på dina pages.

Det kan också hjälpa din site att optimera för search engine genom att göra ditt content mer sökbart och förbättra länkningen mellan blogginlägg.

För att göra din lista över senaste inlägg ännu mer användbar kanske du bara vill visa inlägg som är relevanta för det content som användarna för närvarande viewar.

Showing recent articles from a category to boost pageviews

Detta enkla steg kan uppmuntra visitorerna att spendera mer tid på your site, vilket till och med kan lead till fler email prenumeranter och customers.

Om du nu vill visa alla dina posts från en viss kategori på en separat page, WordPress tar redan hand om detta åt you.

För att hitta kategorisidan behöver du bara gå till Posts ” Categories ” View page och klicka på länken ’ View ’ under en kategori.

View posts by category

Med detta sagt, låt oss ta en titt på hur du enkelt kan visa senaste inlägg efter kategori i olika områden på din website. Vi kommer att täcka följande metoder, så att du kan hoppa till den som intresserar dig:

Metod 1: Lägga till senaste inlägg efter kategori med Block Editor

Som standard levereras WordPress med blocket Senaste posterna i Block Editor. Det allow you att enkelt visa senaste inlägg på en page eller post, och du kan även filtrera dem by category.

Först måste du edit inlägget eller page där du vill visa de senaste inläggen per kategori. På vyn för redigering av post klickar du på knappen add new block (+) och letar sedan efter blocket ”senaste posts”.

Latest posts block

Du kommer att se blocket visas i innehållsområdet med en preview av dina senaste inlägg. Klicka bara för att selecta blocket, så ser du blockinställningarna i den högra colonnen.

Högst upp i inställningarna ser du olika alternativ som att visa utvalt inlägg, författare till inlägg, datum och content.

Sort by category

Nu måste du rulla ner till sektionen Sortering och filtrering under blockinställningarna. Härifrån måste du enter namnet på den kategori du vill visa post från.

Du kan även välja flera kategorier genom att separera kategorinamnen med ett kommatecken.

You’ll notice the preview of your recent posts will change to only include posts from the categories you have chosen.

You can now save your post or page and preview it in a browser window. Så här såg det ut på vår testsite som visar senaste inlägg från en specifik kategori med utvalda images och excerpt av inlägg.

Displaying latest posts by category

Metod 2: Lägga till senaste inlägg efter kategori i WordPress Sidebar

Den här metoden rekommenderas för användare som vill visa senaste inlägg från specifika kategorier i sin sidebar i WordPress.

Gå bara till sidan Appearance ” Widgets och add blocket ’Latest Posts’ till din sidebar.

Adding latest posts block to a sidebar widget

Som standard kommer blocket att visa dina senaste inlägg. You edit the block settings and scroll to the ”Sorting & Filtering” section.

Härifrån kan du välja den kategori som du vill visa posterna från.

Select category

Alternativt kan du välja att visa featured image, excerpt, författare och mer.

Glöm inte att klicka på knappen ”Update” för att publicera dina ändringar.

Du kan nu besöka din website för att se dina senaste inlägg filtrerade by kategori.

Recent posts by category in sidebar

Metod 3: Lägga till senaste inlägg efter kategori med hjälp av kod

Den här metoden kräver att du manuellt addar kod till din website i WordPress. Om du inte har gjort det tidigare kan du läsa vår guide om hur du copy and pastear code snippets i WordPress.

Först måste du copy and paste följande kod i functions.php-filen i ditt WordPress theme eller i ett code snippets plugin.

function wpb_postsbycategory() {
// the query
$the_query = new WP_Query( array( 
    'category_name' => 'travel', 
    'posts_per_page' => 5 
) ); 
   
// The Loop
if ( $the_query->have_posts() ) {
    $string .= '<ul class="postsbycategory widget_recent_entries">';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
            if ( has_post_thumbnail() ) {
            $string .= '<li>';
            $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</a></li>';
            } else { 
            // if no featured image is found
            $string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
            }
            }
    } else {
    // no posts found
 $string .= '<li>No Posts Found</li>';
}
$string .= '</ul>';
   
return $string;
   
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts', 'wpb_postsbycategory');

Glöm inte att ersätta ”travel” med din egen kategoris slug (kategorinamnet som används i URL:er) och save dina ändringar.

Tips: Du kan också add to flera kategorier separerade med ett kommatecken.

Vi rekommenderar att du lägger till den här koden med hjälp av WPCode, det bästa code snippets pluginet. Det allow you to safely add code in WordPress, without editing your functions.php file. Så du behöver inte oroa dig för att förstöra din site.

För att komma igång måste du installera och aktivera det gratis pluginet WPCode. Om du behöver hjälp kan du läsa denna tutorial om hur du installerar ett plugin för WordPress.

Efter aktivering, gå till Code Snippets ” + Add Snippet från WordPress dashpanelen.

Detta kommer att ta dig till Add Snippet page. Härifrån hittar du alternativet ”Add Your Custom Code (New Snippet)” och klickar på knappen ”Use Snippet” under den.

Add new snippet

Next, add a title for your snippet, which can be anything to help you remember what the code is for.

Klistra sedan in koden ovan i ”Code Preview” boxen och välj ”PHP Snippet” som code type från dropdown-listan till höger.

Paste snippet into the WPCode plugin and choose code type

Därefter togglar du omkopplaren från ”Activate” till ”Inaktiverad” och trycker på knappen ”Save Snippet”.

Activate and save snippet in WPCode

Denna kod ber helt enkelt WordPress att visa 5 senaste inlägg från kategorin ”news”. Den visar sedan dessa posts som en punktlista med utvalda images i thumbnail-storlek.

Slutligen skapar den en shortcode [categoryposts] som du addar till en page, post eller sidebar widget. Nu ska vi visa you hur du använder den här shortcoden.

Använda shortcode för att lägga till senaste inlägg efter kategori till inlägg och sidor

Bara edit inlägget eller page där du vill visa de senaste inläggen per kategori. På vyn för redigering av post klickar du på knappen add new block (+) och lägger sedan till Shortcode-blocket i din content area.

Adding shortcode to display posts from a category

Därefter måste du add shortcode [categoryposts] i blockets inställningar.

You can now save your post or page and preview it to see your senaste inlägg från en specifik kategori in action. Så här såg det ut på vår test site.

Posts by category code method with no styling

Som du kan se ser stylingen inte så snygg ut. Oroa dig inte, du kan ändra det genom att lägga till lite custom CSS-kod i ditt theme.

Helt enkelt, gå till Appearance ” Customize page för att starta theme customizer och sedan byta till ”Additonal CSS” tabs i den vänstra kolumnen.

Adding custom CSS code to your theme

Du kan add to följande custom CSS-kod som en utgångspunkt.

ul.postsbycategory {
list-style: none;
}
.postsbycategory li {
padding-bottom:5px;
}
.postsbycategory img {
margin-right:5px
}

Glöm inte att klicka på knappen ”Publicera” för att spara din customize CSS-kod. You can now visit your post or page to view your senaste inlägg styled a bit more neatly now.

Recent posts by category with styling

Lägga till Shortcode för senaste inlägg efter kategori till WordPress Sidebar

You can add the same shortcode to your WordPress sidebar or any widget-ready area.

Gå bara till sidan Appearance ” Widgets och add blocket ’Shortcode’ till din sidebar.

Adding shortcode to sidebar

You can now paste your shortcode [categoryposts] to the block settings. Glöm inte att klicka på knappen Update för att lagra dina inställningar för widgetar.

You kan nu besöka din website för att se dina senaste inlägg per kategori widget i action. Så här såg det ut på vår test website.

Sidebar recent posts by category preview

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du visar senaste inlägg från en specifik kategori i WordPress. Du kanske också vill se vår guide om hur du visar anpassat content till olika användare i WordPress, och vår lista över de bästa WordPress block plugins för att ytterligare customize din site.

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

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

    • WPBeginner Support says

      If you mean the date the post was published, the recent post block has an option where you can enable that to display!

      Administratör

  2. Victoria says

    Thank you for a super helpful post! I always find your content really useful. I’ve added the “Latest Posts” block to a new page and entered the category I’d like to appear on that page. It worked! Question though: how can I display more than 100 posts? Is there any way to do that? The number seems to be capped… thanks again! Any help you can offer is greatly appreciated. Perhaps I need a plug-in for this?

    • WPBeginner Support says

      That many posts on one page could slow your site down which is why there is normally a cap. We do not have a recommended plugin for listing that may posts at one time at the moment.

      Administratör

  3. Jade New says

    Another great post, thanks a lot – I was messing around this for hours yesterday when it’s so super easy! Your blog is in my bookmarks.

  4. Erietta says

    Thanks for this article and showing all the options. I have created two different article landing pages for a website each with different categories using a block. So far so easy. Unfortunately this meant that the default blog archive with all its useful controls didnt suit my needs. What I need now is the ability to add pagination to these pages — but I can’t. Any tips?

    • WPBeginner Support says

      For the moment, you would need to create category pages for the pagination you’re looking for. You can do that by adding a category to your menu.

      Administratör

  5. Rob says

    If i have multiple categories, say categories X,Y & Z, and add them to the snippet code – will this display ONLY the posts for that category – so if I’m viewing a post from category X, it will only display other posts from category X and not from category Y & Z… likewise, if i am in Y it will only display posts from Y?

  6. Akshay says

    The font style is totally different from the default. How to change it as per the theme or what is the css for it.

    • WPBeginner Support says

      You would want to reach out to your theme’s support to ensure there isn’t conflicting styling.

      Administratör

    • WPBeginner Support says

      Hi Ledge,

      These lines are probably added by your theme using CSS. You can use Inspect tool to find out the CSS responsible for that and then add custom CSS to override this.

      Administratör

  7. Allen S says

    I have just started to use Recent Posts Extended widget but for some reason i can’t get it do display what i want and where i want it to go. I run a driving school and have built my website using WP & Divi Builder. I have 7 Recent Posts Extended. One for latest customer reviews to appear on home website page for all areas served, 3 for test passes and 3 for customer reviews for 3 areas I cover which have their own page. But when I go to select the area in “limit to category” for each Recent Posts Extended I expected to see 7 categories with check boxes and there are only 5 categories available for selection. I am no developer, so understanding CSS code to use is like reading Chinese. I have trawled the web and not found the answer to suit my needs.

  8. Alex M. says

    Hello, thanks for this snippet. Is there any way to display posts from a specific category but if there isn’t enough with that category it will show the regular posts?

    For example I have one post with the ”featured” category checked but on my homepage I need to display 3 posts, that leaves me with 2 empty spots.

    Thanks! :)

  9. Shahbaz says

    If I want to display post of perticular category on a new page then where should i copy those snippets

  10. Mags Nixon says

    I’ve just activated this plug in and worked fine for the first sidebar. The second customised sidebar just showed the category of the first one. I ended up deleting the second one but now it’s not showing at all. Have you had any other feedback about this widget now not being supported by wordpress since the latest updates? Any advice would be appreciated.

  11. Zelaphas says

    Thanks for this. I’m using this with the ”Sydney” WP theme and trying to have certain categories of projects on the home page as portfolio/case studies. I successfully got the widget to show along with my desired posts, but they’re displaying vertically. I’d like them to be right next to each other horizontally in a grid (unless on mobile, of course). Any ideas on this? Thanks!

  12. hailemaryam says

    thank you!!! you saved my life i was working on customers website and the need only news to be showed on the slider. you showed me a way how to customize it.

  13. Debora says

    Hi, thank you for the tutorial. Only a question: I’m trying to get a carousel of latest posts in homepage with preview image. All plugins I have tried had bad image layout, I have many images with different sizes. So I wanted to try without plugin, only write code in wp.
    Can you please tell how to add preview images to your code, to display recent posts with preview image? Thank you very much

  14. ben says

    Hello,

    Did you try this plugin (last update 1 year ago) with the last update of WordPress?
    When I check the support in wordpress, it’s seems this plugin is not support anymore and some users can’t use it correctly with recent WordPress.

    Best Regards

  15. Theo Dorant says

    If you want to have your code in functions.php, you can use

    function include_posts_from_recentPostWidget_by_cat() {
    $include = array( ’cat’ => ’2, 5’ );
    return $include;
    }
    add_filter(’widget_posts_args’,’include_posts_from_recentPostWidget_by_cat’);

    2 and 5 are the IDs of the categorys you want to show. You can do the same to exclude categories by using ’-2, -5’

  16. Blair Jersyer says

    What if that post where we’re showing the recent posts is part of recent post and if we’re show the_content()… There won’t be unlimited loop ?

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.