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 numerisk sidonumrering i ditt WordPress Theme

Vill du add to numerisk sidonumrering i ditt WordPress theme?

Som standard lägger WordPress themes till en Next / Previous links längst ner på archive pages. Utmaningen är att dessa inte är särskilt användarvänliga. Det är därför många populära bloggar använder numerisk sidonumrering för att göra det lättare för besökare att navigera på sina archive pages.

I den här artikeln visar vi hur du addar numerisk sidonumrering i ditt WordPress theme.

How to add numeric pagination in your WordPress theme

Varför lägga till numerisk sidonumrering i ditt WordPress Theme?

De flesta teman har en page archive som visar en lista över posts. När du publicerar fler blogginlägg på WordPress kommer din archive page att omfatta flera pages.

Links för sidonumrering hjälper besökarna att flytta mellan pages i archive och visas vanligtvis längst ner på din WordPress website.

Vissa WordPress teman använder ”Äldre inlägg” och ”Nyare inlägg” links för sidonumrering. Detta låter dock bara besökaren gå framåt och bakåt med en page.

Den visar inte heller besökarens nuvarande location i archive. Detta kan göra det svårare för besökare att navigera i din bloggs archive.

Det är där numerisk sidonumrering kommer in i bilden.

Istället för att visa ”Older” och ”Newer” links, visar numerisk sidonumrering en serie siffror som låter visitorerna hoppa till en specifik page i archive.

Numerisk sidonumrering kan också använda högdagrar eller olika färger för att visa den aktuella sidans nummer, så att besökaren alltid vet exakt var i arkivet han eller hon befinner sig.

På WPBeginner använder vi numerisk sidonumrering och markerar det aktuella sidnumret i orange. Vi ger också direkta links till de 4 pages som omger besökarens aktuella page.

Vi har till och med en länk till den sista page i vårt archive, så att visitorerna snabbt och enkelt kan se våra tidigaste posts, som du kan se i följande image.

Numeric pagination links on the WPBeginner website

Enligt vår erfarenhet gör den här typen av numerisk sidonumrering din site enklare att navigera på jämfört med standardlänkarna ”Äldre inlägg” och ”Nyare inlägg”.

Om your WordPress theme har ”Older” och ”Newer” sidonumrering rekommenderar vi alltid att du ersätter den med numerisk sidonumrering.

I den här guiden kommer vi att täcka två olika sätt att add to numerisk sidonumrering i ditt WordPress theme. Om du föredrar att hoppa direkt till en viss metod kan du använda länkarna under.

Metod 1. Hur man addar numerisk sidonumrering i WordPress med WP-PageNavi

Det enklaste sättet att add to numerisk sidonumrering i WordPress är att använda pluginet WP-PageNavi.

För att använda detta plugin måste du fortfarande göra några ändringar i ditt temas kod, men det är mycket enklare än den fullständiga kodmetoden eftersom WP-PageNavi ger dig fullständig control över din sites sidonumrering.

Det första du behöver göra är att installera och aktivera WP-PageNavi plugin. För mer detaljer, vänligen se vår steg-för-steg guide om hur man installerar ett WordPress plugin.

När du har aktiverat pluginet går du till Settings ” PageNavi för att konfigurera plugin-inställningarna.

How to add numeric pagination in WordPress

Här kan du ersätta texten i sidonumreringen som är standard med din egen text. You kan t.ex. ändra den text som din website använder för länkarna ”First Page” och ”Last Page”.

Du kan också customize de numeriska länkarna för sidonumrering.

I sektionen ”Number Of Pages To Show” kan du välja hur många pages pluginet ska visa i din websites sidonumrering.

The WP-PageNavi WordPress plugin

Som standard är den inställd på 5, vilket innebär att WP-PageNavi visar direktlänkar till 5 pages.

Som du kan se i screenshot under att om du är på sidan 4, så kommer du att se links till pages 2, 3, 4, 5 och 6.

An example of numeric pagination in WordPress

You kanske vill visa fler pages eller färre pages. För att göra denna ändring skriver du helt enkelt in det nya antalet i fältet ”Number Of Pages To Show”.

Som standard visar pluginet flera större nummer. Detta gör att besökare kan gå vidare med flera pages, med bara ett click.

Som standard visar pluginet tre större siffror som ökar med 10 varje gång. Till exempel 10, 20 och 30.

Vill du använda ett annat intervall, t.ex. 5 eller 20? Skriv då bara in det nya intervallet i fältet ”Visa större sidnummer i multiplar av”.

Customizing the WordPress pagination settings

Alla WordPress webbplatser är olika, så det är en bra idé att prova olika settings för att se vilka inställningar för sidonumrering som fungerar bäst för you.

Om du har gjort några ändringar i WP-PageNavi-inställningarna, glöm inte att rulla längst ner på sidan och klicka på knappen Save Changes.

Därefter måste du lägga till en template tag i ditt WordPress theme. För att göra detta rekommenderar vi att du skapar ett barntema och sedan editerar koden för barntemat.

Genom att skapa ett barntema kan du fortfarande uppdatera ditt WordPress-tema på ett säkert sätt utan att förlora din customze numeriska sidonumrering. Om du vill veta mer kan du läsa vår steg-för-steg guide om hur du skapar ett WordPress barntema.

Oavsett om du väljer att edit ett huvudtema eller ett barntema behöver du en FTP-klient. Om det är första gången du använder FTP kan du se vår kompletta guide om hur du ansluter till din webbplats med FTP.

När du är ansluten till ditt WordPress webbhotell konto via FTP, är du redo att editera koden för ditt WordPress theme.

Dessa steg varierar beroende på ditt WordPress-tema. Du behöver dock vanligtvis editera koden i filen index.php eller archive.php, plus eventuella andra filer med templates för archive i ditt WordPress-tema.

Öppna bara dessa filer och sök sedan efter taggarna previous_posts_link och next_posts_link.

Om du hittar dessa taggar ska du ersätta dem med följande code snippet:

<?php wp_pagenavi(); ?>

Vissa themes kanske ej har en previous_posts_link eller next_posts_link tagged.

Om du inte kan hitta dessa tags i ditt theme, leta då efter the_posts_navigation istället. Du hittar till exempel följande i filen archive.php i temat Twenty Twenty-One:

<?php /*twenty_twenty_one_the_posts_navigation();*/ 

Du kan sedan gå vidare och ersätta den här raden med följande code snippet:

<?php wp_pagenavi(); ?>

När du har gjort dessa ändringar ska du save och sedan close alla öppna WordPress theme-filer.

Nu, om du besöker din WordPress archive page bör du se din new numeriska sidonumrering live på din website.

Klart är att du kanske vill ändra färg och stil på den numeriska sidonumreringen så att den passar bättre in i ditt theme eller på din website.

Du kan göra detta genom att editera koden för pluginet.

Vi rekommenderar dock att du klistrar in WP-PageNavi-koden i ditt temas style.css-fil och sedan gör dina ändringar i temafilen. Detta innebär att du inte kommer att förlora dina customizes när du uppdaterar WP-PageNavi-pluginet.

För att kopiera din plugin-kod, head över till Settings ” PageNavi. You can then find the ”Use pagenavi-css.css” section and click on the ”No” radio button next to it.

Glöm inte att clicka på knappen ”Save Changes” för att spara dina ändringar.

Changing your WordPress pagination styling

Gå sedan till Plugins ” Plugin File Editor.

Du kan sedan öppna dropdown ’Select plugin to edit’ och välja ’WP-Page Navi’. Efter det är du redo att klicka på ”Select”.

The WordPress code editor

I menyn till höger klickar du på filen pagenavi-css.css.

Gå sedan vidare och kopiera all kod i den här filen.

The WordPress plugin editor

Därefter går du helt enkelt till Appearance ” Theme File Editor.

I den högra menyn klickar du på filen style.css i ditt theme.

The WordPress theme editor

Du kan nu klistra in din pagenavi-css.css-kod i temats style.css-fil och börja göra dina ändringar.

Låt oss titta på ett exempel. Här är en ändrad version av koden för numerisk sidonumrering som du kan add to your themes style.css-fil:

wp-pagenavi {
    clear: both;
}
 
.wp-pagenavi a, .wp-pagenavi span {
    color: #FFF;
    text-decoration: none;
    background-color:#6FB7E9;
    border: 1px solid #B2D1E5;
    padding: 5px 5px;
    margin: 2px;
}
 
.wp-pagenavi a:hover, .wp-pagenavi span.current {
    border-color: #E9F2F9;
    background-color:#6FB7E9;
}
 
.wp-pagenavi span.current {
    font-weight: bold;
    background-color:#3C8DC5;
}

I följande image kan du se hur denna numeriska sidonumrering kommer att se ut på din site.

Custom numeric pagination in a WordPress theme

Det är värt att prova olika stilar för att se vad som ser bäst ut på din WordPress website.

När du är nöjd med hur din numeriska sidonumrering ser ut klickar du på knappen Update File för att save dina ändringar.

Metod 2. Så här lägger du till numerisk sidonumrering manuellt i ditt WordPress Theme

Ett annat alternativ är att manuellt lägga till numerisk sidonumrering i ditt WordPress theme med hjälp av kod.

Många teman i WordPress har inbyggda ”Older” och ”Newer” links, eller numerisk sidonumrering som standard. Till exempel lägger det populära temat Astra automatiskt till sin egen numeriska sidonumrering på dina pages archive, som du kan se i följande image.

Pagination in the Astra WordPress theme

Du kan använda den här metoden för att customize ett temas built-in sidonumrering. Du kan till exempel ändra stylingen så att den passar din site bättre.

För att manuellt add to numerisk sidonumrering öppnar du functions.php-filen i ditt theme. Här kan du använda antingen en FTP-klient eller filhanteraren i cPanel på ditt webbhotell i WordPress. Om du använder FTP kan du se vår kompletta guide om hur du ansluter till din site med FTP.

När du har anslutit till din site utan problem öppnar du filen functions.php och add to följande kod:

function wpbeginner_numeric_posts_nav() {
 
    if( is_singular() )
        return;
 
    global $wp_query;
 
    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;
 
    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );
 
    /** Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;
 
    /** Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }
 
    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }
 
    echo '<div class="navigation"><ul>' . "\n";
 
    /** Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '<li>%s</li>' . "\n", get_previous_posts_link() );
 
    /** Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';
 
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
 
        if ( ! in_array( 2, $links ) )
            echo '<li>…</li>';
    }
 
    /** Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }
 
    /** Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '<li>…</li>' . "\n";
 
        $class = $paged == $max ? ' class="active"' : '';
        printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }
 
    /** Next Post Link */
    if ( get_next_posts_link() )
        printf( '<li>%s</li>' . "\n", get_next_posts_link() );
 
    echo '</ul></div>' . "\n";
 
}

Den här koden ger antalet pages, redo för dig att visa i ditt WordPress theme.

Nästa steg varierar beroende på ditt theme.

Om ditt tema inte har någon form av standardtema för sidonumrering built-in, kan du helt enkelt add to följande template tag i index.php, archive.php, category.php eller någon annan page där du vill visa numerisk sidonumrering.

<?php wpbeginner_numeric_posts_nav(); ?>

Tänk bara på att var du lägger till den här koden kommer att påverka var den numeriska sidonumreringen visas på din website.

Vanligtvis vill du visa sidonumreringen längst ner på dina archive pages, så du vill vanligtvis lägga till template tagged i din footer code.

Har ditt theme redan någon form av sidonumrering, till exempel länkar till ”Äldre inlägg” och ”Nyare inlägg”?

I det här fallet måste du hitta koden för sidonumrering och ersätta den med snippet ovan.

Ashe är till exempel ett av de bästa gratis WordPress blogg themes och lägger redan till ”First” och ”Last page” sidonumrering länkar till dina archive pages.

För att ersätta dessa built-in links med numerisk sidonumrering måste du editera temats templates/grid.php och templates/blog-pagination.php-filer.

I var och en av dessa filer hittar du helt enkelt följande section:

<?php get_template_part( 'templates/grid/blog', 'pagination' ); ?>

Du kan sedan gå vidare och ersätta den här raden med följande code snippet:

<?php wpbeginner_numeric_posts_nav(); ?>

När du har addat koden, glöm inte att save dina ändringar.

Nästa steg är styling av din custom numeriska sidonumrering.

För att hjälpa visitorerna att navigera i archive kommer vi att markera det aktuella sidnumret med en annan färg. För att göra detta, öppna ditt temas style.css-fil och klistra sedan in följande kod i den här filen:

.navigation li a,
.navigation li a:hover,
.navigation li.active a,
.navigation li.disabled {
    color: #fff;
    text-decoration:none;
}
 
.navigation li {
    display: inline;
}
 
.navigation li a,
.navigation li a:hover,
.navigation li.active a,
.navigation li.disabled {
    background-color: #6FB7E9;
    border-radius: 3px;
    cursor: pointer;
    padding: 12px;
    padding: 0.75rem;
}
 
.navigation li a:hover,
.navigation li.active a {
    background-color: #3C8DC5;
}

Efter alltihop är det bara att save dina ändringar genom att clicka på knappen Update File.

Om du nu besöker sidan archive ser du den numeriska sidonumreringen live på din website.

Manually adding numeric pagination in WordPress

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du addar numerisk sidonumrering i ditt WordPress theme. You can also go through our guide on ways to make money online blogging with WordPress and how to create a custom WordPress theme without writing any code.

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

120 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. Kzain says

    this is helpful but how do I know if my theme works with pagination? and what happens if I use the Elementor paginations button to related post section

    • WPBeginner Support says

      If your theme or page builder already has a pagination option, we would recommend using that first instead of the method from this guide :)

      Administratör

  3. Jiří Vaněk says

    I use the Generate Press theme, and I found a snippet that works great for extending the pagination bar to more pages. However, I now see, according to this article, that I could also customize the pagination bar to match the look of my website. I will probably very soon try your guide on customization and will try to style the bar better to match the colors of my site. It is a minor detail, but this bar is quite visible and important. Thanks.

  4. Sujal says

    There’s little bug in last lines which shows next link. You’re missing $ sign at two places get_next_posts_link() . Can you please fix that so code works well for new visitors :-)

    /** Next Post Link */
    if ( $get_next_posts_link() )
    printf( ’%s’ . ”\n”, $get_next_posts_link() );

    • WPBeginner Support says

      Your theme may have some custom styling, you would want to reach out to your theme’s specific support and they should be able to assist.

      Administratör

  5. Quy says

    thanks.
    Normally, home.php will show up the loop content for Post page, but since my theme does not provide home.php by default so I put the wpbeginner_numeric_posts_nav(); at index.php (below endwhile;) and it works.

  6. ModGirl says

    I’m using the wordpress theme ”X Blog” and I’m trying to figure out how to add this to that theme. everything I try keeps giving me errors. not sure why the theme won’t work with this. any help would be appreciated. thanks

  7. Adam says

    This is a really useful tutorial, thanks. I used the genesis code example with success!

    My one issue was that simply copying and pasting the code from this site caused an encoding error for where the ellipses go in the numbered pagination. So on the site it displayed a diamond/question mark character instead of the ellipsis. I ended up using the HTML Entity (decimal) ellipsis: … instead which fixed this error. This only occurred on one of the two sites implemented this code on probably due to differences in meta charset or something.

  8. Sijo says

    Pagination not working after page2. It’s showing 404 page when click 3 ,4 etc… I have used the same code above. How can i resolve this ?

  9. Jean Braithwaite says

    I am using your manual method for pagination, and you say ”add the following template tag in your theme’s index.php, archive.php, category.php, and any other archive page template”.

    The site is a regular website along with a blog which uses a custom post type.

    It worked well on my archive.php page, but I would also like to use it on my blog page, which is a page template, page-blog.php. I can’t get it to work there at all. Why is that? Is there something I can do to get it working?

  10. ziru says

    hello, I added to some templates and my wordpress couldn’t work anymore, not even login in and my homepage turn to a blank page and seems the whole website break down, what can I do?

  11. Ingy Anees says

    This is working fine with me in custom post type but can’t get it to work with search results .. nothing is shown at all. and advice ?

  12. souno says

    Very nice article and i have a question.

    How to show total number of pages at last? In your demo it shows ”9”

    Thank You!

  13. Andy says

    Like Rajath I had a few problems with the pagination not rendering well on mobiles. In my case the lines overlapped. I resolved this by adding a line height to the CSS:

    line-height: 2.5em;

  14. mostafa says

    Hi, I ’ve used this code for my theme (without wp-nav plugin) ,it works other pages except in front page .what is exactly the problem?

  15. Rajath says

    Hi i`m using this pagination in my theme and it works fine in all pages and categories except in the pages where i`m using custom wp_query. I`ve read that you are using a code similar to the one in genesis framework and i`ve used wp_reset_query() but it isn`t working. Thanks in advance for the help.

  16. anuj sharma says

    hi
    i m using your given code and paste in function .php and also add css in style.css but this shows pagination design but its not working

  17. JM says

    Hello! First off, I want to thank you for posting this. I know that this post is now pretty old, but it is still very useful!

    The pagination displays and functions fine for the most part; but the first and last page links are missing for me. It does not matter which page I am on (first, second, third, etc.), no first page or last page links show up. Any ideas on how I can fix this?

    Thanks in advance for any help!

  18. Syed Hamza says

    Numeric Pagination shows only on PC but doesn’t show on mobile. I want to show this pagination on both versions.
    How I can fix it?

    • JeffD says

      Thank you so much for the excellent tutorial. I want to use the non-plugin solution (the php script), but with no truncation/ellipses for page links (instead of 1…2 3 4 5 6…10, I want to just show all pages all the time – 1 2 3 4 5 6 7 8 9 10). How can I modify the script to do this? Should be easy for you experts but not for me! Thank you in advance for any helps!

  19. Youssef says

    Hi I want return default wp pagination in my theme” freshlife by theme junkie I don’t Like the numeric pagination because it show the total posts in my website . please wpbeginne help

  20. Rajath says

    Hi, NIce tutorial and your website have helped me in many issues while developing my own theme. I have opted for the manual pagination shown here instead of plugin. But the pagination is not responsive and looks bad when the screen size is reduced. How to make it responsive or are there any other alternatives(no plugins please).I`m not going to publish this theme so i`m building it just to suit my need…

    • WPBeginner Support says

      Look at your WordPress theme’s stylesheet. Study how your theme handles responsiveness. Some themes use media queries to detect screen width and then adjust different elements accordingly. Some themes use relative widths to make sure that all elements inside their design layout are responsive to the screen width.

      Administratör

      • Rajath says

        I’m developing the theme. I’m unable to make the pagination responsive. So I just removed the padding around the links which make them to look like a button. Instead I left them like numbers which works fine in small screens too. Thank You for the reply.

  21. James says

    I’m trying to remove the pagination from my homepage found below each summary post, to me it doesn’t look great, is there a way to do this.

  22. Aryan says

    Actually i am new to wordpress but i know php good……i want to add a pagination from custom table in data base……

  23. Fasih says

    the numbered pagination without the plugin is working fine on localhost but when i upload the files i cant see anything but when i check the inspect element, the only thing i found was an empty div containing the classes but with nothing inside it. i have uploaded all the files correctly and double checked but not successful. please guide me

  24. Moustafa says

    This script does not work in the new WordPress 4.3.1
    omdat bij de oude versie heeft die script wel gewerkt en nu niet meer

    Pleas help…

  25. Med says

    Hello,

    I found this very useful and I placed it to my new site. The problem is that it works perfect on the first page of the category, and after clicking on the ”Next” link the url changes to /page/2/ but the highlighted page number is aways ”1” and the content is always the first 10 articles (always in the first page).

    I think there is something missing in my query:

    <a href="”>

    ’aligncenter’));

    } else {

    echo ”;

    }

    ?>


  26. Preeti Bhandari says

    how can i prevent whole page reload when clicking on next link, only want to refresh that particular section… Please help….

  27. Luis Eduardo Braschi says

    Because ”the goal is to replace the default Older and Newer pagination links at the bottom of archive pages” – and this is what ”your” function does – ”with easy to navigate page numbers.”.

  28. Barry says

    How can i use the wpbeginner_numeric_posts_nav(); for my Custom Post type?

    I have replaced global $wp_query for

    $args = array(

    ’post_type’ => ’my-cpt’,

    ’meta_key’=>’cpt_detail’,

    ’orderby’=>’meta_value’,

    ’order’ => ’ASC’,

    ’paged’ => $paged

    );

    $cpt_query = new WP_Query($args);

    and replaced $wp_query reference with $cpt_query but it doesn’t work

    • igloobob says

      Hi, did you ever figure this out please? I’m trying to get this working myself and struggling. Would appreciate your help very much if you got it working…

    • James George Dunn says

      Hello Ashley,

      You can set a value in the brackets of get_previous_posts_link() and get_next_posts_link(). For example, get_next_posts_link(’Next Post’) will show ”Next Post” instead of the default ”Next Page »”.

    • TimParkerRD says

      If you’re using the wpbeginner_numeric_posts_nav function, you can pass custom text to the get_next_posts_links() and get_previous_posts_link(), like so:

      get_previous_posts_link(”Go Back”);

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.