Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Puchar WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Jak wyświetlać podkategorie na stronach kategorii w WordPress?

W WPBeginner zawsze szukamy nowych i lepszych sposobów na ulepszenie nawigacji i pomoc użytkownikom w znalezieniu dokładnie tego, czego potrzebują.

Na szczęście WordPress ułatwia organizowanie twoich wpisów za pomocą kategorii i podkategorii. Wyświetlanie podkategorii bezpośrednio na stronach kategorii to skuteczny sposób na poprawę komfortu użytkowania i ułatwienie nawigacji po twojej witrynie internetowej WordPress.

W tym artykule pokażemy, jak wyświetlać podkategorie na stronach kategorii w WordPress. Dostarczymy ci kod i instrukcje, których potrzebujesz.

Display Subcategories on Category Pages in WordPress

Dlaczego warto wyświetlać podkategorie na stronach kategorii?

Pisząc wpisy na twoją witrynę internetową WordPress, możesz zoptymalizować ją pod kątem wyszukiwarek i poprawić nawigację po witrynie poprzez odpowiednie kategoryzowanie treści. Zwiększy to ruch na twojej witrynie i pozwoli odwiedzającym łatwiej znaleźć treści, których szukają.

Na niektórych witrynach internetowych sensowne jest stosowanie podkategorii w celu uproszczenia struktury witryny.

Na przykład możesz mieć kategorię nadrzędną o nazwie Sport. Następnie możesz mieć podkategorie w kategorii Sport o nazwach NFL, NBA i MLB.

Example of Using Subcategories in WordPress

Gdy odwiedzający twoją stronę klikną kategorię Sport, zobaczą każdy wpis w kategorii Sport i jej podkategoriach. Nie zobaczą jednak listy podkategorii. Utrudnia to filtrowanie wpisów tylko do NFL lub NBA.

Wyświetlanie listy podkategorii na twoich stronach kategorii może poprawić nawigację w witrynie. Jest to szczególnie ważne, jeśli zdecydujesz się ukryć podkategorie w widżecie kategorii twojej witryny internetowej.

Show Only Top Level Categories

Na przykład, odwiedzający twoją witrynę mogą łatwo przejść od wszystkich wpisów sportowych do tylko NFL. Co więcej, możesz nadal wyświetlać te same podkategorie na stronie NFL, aby mogli łatwo przełączać się z NFL na NBA.

W związku z tym przyjrzyjmy się, jak wyświetlać podkategorie na stronach kategorii w WordPress.

Jak wyświetlać podkategorie na stronach kategorii w WordPress?

Aby wyświetlać podkategorie na stronach archiwum kategorii, musisz dodać kod do plików twojego motywu. Jeśli potrzebujesz pomocy w dodaniu kodu do twojej witryny, zapoznaj się z naszym przewodnikiem dla początkujących na temat wklejania fragmentów kodu z sieci do WordPressa.

Pierwszą rzeczą, którą musisz zrobić, to wejść do katalogu twojego motywu i poszukać pliku archiwum kategorii o nazwie category.php.

Jeśli nie widzisz tego pliku, musisz go utworzyć. Wystarczy zduplikować archive.php i nazwać go category.php.

Uwaga: Jeśli twój motyw nie zawiera pliku category.php lub archive.php, to prawdopodobnie korzystasz z frameworka motywu WordPress i będziesz musiał utworzyć plik category.php ręcznie. Dobrym punktem wyjścia do nauki tworzenia plików archiwum jest nasz przewodnik na temat tworzenia własnych stron archiwum w WordPress.

Teraz wystarczy dodać następujący kod do pliku category.php tuż przed pętlą:

<?php
if (is_category()) {
    $this_category = get_category($cat);
    }
    ?>
    <?php
    if($this_category->category_parent)
    $this_category = wp_list_categories('orderby=id&show_count=0
    &title_li=&use_desc_for_title=1&child_of='.$this_category->category_parent.
    "&echo=0"); else
    $this_category = wp_list_categories('orderby=id&depth=1&show_count=0
    &title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID.
    "&echo=0");
    if ($this_category) { ?> 
 
<ul>
<?php echo $this_category; ?>
 
</ul>
 
<?php } ?>
Add the Code Snippet to category.php Just Before the Loop

Teraz, gdy przejdziesz na stronę kategorii, zobaczysz listę podkategorii.

Na naszej witrynie demonstracyjnej strona kategorii Sport zawiera odnośniki do podkategorii NFL, NBA i MLB.

Preview of Subcategories on Category Page

Po kliknięciu odnośnika NFL zostaniesz przeniesiony na stronę podkategorii NFL.

Tutaj nadal widoczne są odnośniki do podkategorii Sport, dzięki czemu można łatwo przełączać się między różnymi rodzajami sportów. Może to naprawdę uprościć nawigację na twojej witrynie.

Preview of Subcategories on Subcategory Page

Przewodniki ekspertów dotyczące kategorii i podkategorii w WordPressie

Teraz, gdy już wiesz, jak wyświetlać podkategorie na stronach kategorii, możesz zapoznać się z innymi przewodnikami związanymi z wyświetlaniem kategorii i podkategorii w WordPress.

Mamy nadzieję, że ten poradnik pomógł ci dowiedzieć się, jak wyświetlać podkategorie na stronach kategorii w WordPress. Być może zechcesz również dowiedzieć się, jak poprawić SEO twojej witryny internetowej lub zapoznać się z naszą ekspercką listą najlepszych wyskakujących wtyczek WordPress.

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.

Ujawnienie: Nasze treści są wspierane przez czytelników. Oznacza to, że jeśli klikniesz na niektóre z naszych linków, możemy otrzymać prowizję. Zobacz jak WPBeginner jest finansowany, dlaczego to ma znaczenie i jak możesz nas wspierać. Oto nasz proces redakcyjny.

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.

Najlepszy zestaw narzędzi WordPress

Uzyskaj BEZPŁATNY dostęp do naszego zestawu narzędzi - zbiór produktów i zasobów związanych z WordPressem, które każdy profesjonalista powinien mieć!

Reader Interactions

74 komentarzeZostaw odpowiedź

  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. George G.

    Hello,

    I use a theme which does not contain the category.php file. Categories and posts are shown throush a archive.php in which file is located into a plugin framework that comes together with this theme.

    • Nelda

      This is a problem many people run into when they don’t look closely at what their theme provides. I would recommend choosing a different theme and this time look for categories with layers, tags, modifiable menus, block editor, and mobile responsive. Many exist for free that provide these basic functions. It is much easier to move forward and continue to enhance your site using a theme that is supportive of the flexibility you seek, rather than tweak a theme that doesn’t meet your needs out of the box. You will be tweaking continuously in the future, and that is not fun, trust me!!

      This site has posts about responsive themes and the features they provide and after you choose a better theme, here is the link to swap it out. It is a very simple process.
      https://www.wpbeginner.com/beginners-guide/how-to-properly-change-a-wordpress-theme/

  3. Jameel Evans

    I pasted this code into my category.php file, but when I go to mysite.com/category it’s not showing. Any suggestions?

    • WPBeginner Support

      You would want to ensure the code is before the loop in your category.php and if it it placed there correctly then you would want to check with the support for your specific theme to see if they have something that would override the usual display.

      Administrator

  4. Sarah

    I inserted this code via the Code Snippets plugin, which has worked successfully with inserting other code, but now I have what I found out is called the 'white screen of death’! Even on my website page ending in /wp-admin.

    Does anyone know how to fix this when I can’t see my admin dashboard?

    • Em

      open up the file directory and delete the plugin, it would get rid of the issue

  5. Ahmad

    this code does not work that exactly I want, I want a proper arrangement of categories like navigation.
    Parent category
    Grandchild 1
    Grandchild 2
    subchild 1
    sibling categories

  6. Jagdev

    Hello,

    How can we use this for custom post taxonomy created ?

    I want to list the main categories first then sub-categories and sub etc.. untill reach upto post pages?

    Can we change this code for custom post categories?

    Thanks

  7. Don

    Hi! :)
    How exactly should the code be inserted?

  8. Pradeep PL

    But, Not to hide Parent Category, when I click on subcategory page. I want to show all the subcategory in Parent category as well as in subcategory also.

  9. Sveinung Berntsen

    Thanks for this great post. I have managed to make a filter for my category page with this code. But I would like to have a link to show all posts in the main category; if you clicked on one of the subcategory filter links, and want to go back to see all posts for the main category. Kind of like this:
    All (20) Subcategory 1 (12) Subcategory 2 (5). Subcategory 3 (3)

    Is that possible? And how can I get the number as a part of the link?

  10. Julie-Ann

    Hi

    I don’t know anything about coding. I would really like to add subcategories to my wordpress blog so that I can organise my content better. Where do I paste this code to make it work? What exactly will happen. I would like to understand this a bit more please if you are able to assist.

  11. Eliyas Ahmed

    how to hide parent under categorie.

  12. Gustavo Fernandez

    Thanks for the post..
    This works for woocommerce?

    Thanks

  13. Amanda

    I know this is an old post but it is exactly what I am after for a current project.
    Is there anyway to have an image show up with the category.
    I have used this plugin in the past to add an image to a category – Categories Images

    <?php if( function_exists('z_taxonomy_image') AND get_option('z_taxonomy_image'.$cat_id)” ) z_taxonomy_image($cat_id); ?>

    I am just not sure how to implement it with your code.

  14. Lambodar

    Hi,

    Thanks for the code.

    I have Category Structure like:

    Main Category: Home Improvement
    Child Category: Roofing
    Grand Category: Gutters

    On this page: I want to show all child categories, which is fine it displays all.

    On this page: I want to show all grand child categories, but it show all child categories.

    On this page: I want to show nothing, as this is the last

    Pls let me know how to fix it.

    I used your code like this:

    category_parent)
    $this_category = wp_list_categories(’orderby=id&show_count=0&hide_empty=0&title_li=&use_desc_for_title=1&child_of=’.$this_category->category_parent.
    „&echo=0”); else
    $this_category = wp_list_categories(’orderby=id&depth=1&show_count=0&hide_empty=0&title_li=&use_desc_for_title=1&child_of=’.$this_category->cat_ID.
    „&echo=0”);
    if ($this_category) { ?>

  15. Jay

    Call me stupid but where do we put this code, in header.php, index.php. functions.php?

    FYI I have a page where they click an image in the main page and it takes them (currently) to a main category.

    my goal is when they click the image it takes them to a page listing the sub cats for the cat, this will allow sorting of the posts!

  16. Smith

    is it possible to display posts on category pages as subcategory wise using this.

    Example :

    ** Main Category Page **

    ** Sub category #1 **
    – Post #1
    – Post #2

    ** Subcategory #2 **
    – Post #3
    – Post #4

    • Zee

      Did You get any clue on this? I needed this too

    • Asim Khan

      hi did you find any solution to show categories plz reply me

    • Prafulla Kumar Sahu

      Hey, Have you got any solution to this ??

    • Gerd Casper

      Need this too.
      Is anyone able to give a tip?

  17. Monique

    Since wp 4.0 I get the following error if debug is true:

    Notice: get_all_category_ids is niet meer in gebruik sinds versie4.0! Gebruik in plaats daarvan get_terms(). in

    This is the dutch error, in english it says it is depreceated. How can the code be adjusted so it works with the new standard?

  18. carole

    Exactly what I needed except I had to add &hide_empty=0.

  19. Joe Librizzi

    Thanks for this, but changing orderby argument doesn’t seem to be having any impact on the actual displayed order. Has anyone else had a similar issue? Any solutions?

  20. Katia

    Thank you for this helpful post.
    I need to exclude some of the categories , so those will not show . How can I do that?

  21. Catalin

    Hello

    I need some help with the script above. I have a Category list of countries like USA, UK, Italy, France etc. and each country it will have cities as sub categories.
    This script works great, when i click on Italy the cities sub categories appear in the side bar, however when a click on page or inside a post the cities disappear and it show only the country in the side bar.
    How can I modify so when i click over a post inside the cities remain and when i click on a page like About or Home the cities to disappear? Also I use Hueman theme and i will need the cities to appear in the header menu. How much do you charge for that? E-mail me at kid_punky @ yahoo.com

  22. sourabh nigam

    i am using jigoshop plugin for e-eCommerce clothing website
    in the jigoshop category add
    MAN
    WOMAN
    BOYS
    OTHER
    it has also sub category
    i want to display main category in sidebar and when click on category then sub category should be display;

  23. Mitul

    thanks great post, this tricks work but I have question..I want display sub category like your https://www.wpbeginner.com/deals/ category page. please tell me how can I add css and make sections page like your deal page.

    • WPBeginner Support

      Mitul, for CSS you can view it in the source, feel free to play with it. You can use conditional tags in your template to show your sub categories differently or you can create a new template for the subcategory.

      Administrator

  24. pustiu314p

    Hi,
    I use your code with success, and thanls for that.
    I have a little trouble: I removed „depth=”1″ from code but the main category does not appear in sidebar. only subcategories.
    How can I display both the parent category and subcategories?
    Thank you.

      • Pustiu314p

        oh ok, so is any way to display grand-child categories?

  25. rob_mod

    Hi. Will this work with WordPress 3.3.1?

    Also, this question might seem silly, but I want to double check:

    This code will allow subcategories specific to the category page you’re on to appear in the sidebar, correct? Phrased another way: I’m on the homepage. I click on the main navigation which says „Illinois.” That takes me to a (category) archive page for Illinois, that has a sidebar. In that sidebar is: Chicago, Evanston, Skokie (subcategories). Now, If clicked on „New York” in the main navigation, I’d go to a (category) archive page for New York, and in the right hand column for that page would be: NYC, Albany, Buffalo, Rochester.

    Am I correct, or am I misunderstanding the application?

    Thanks so much!

  26. VandeMataram

    comment is not posted correctly … so putting it again:

    Main-Category

    Sub-category-1, Sub-category-2, Sub-category-3, Sub-category-4, Sub-category-5,

    Sub-category-6, Sub-category-7, and so on ………….

  27. VandeMataram

    I want to show list of sub-categories in main category archive page, for example:

    <Main Category>

    <sub-category-1>, <sub-category-2>, <sub-category-3>, <sub-category-4>, <sub-category-5>, <sub-category-6>, and so on …

    I have copied the same code provided in this article, but it’s not working … nothing is displaying in category page.

    Please help.

  28. robolist

    Hi there, I am hoping there is a fix for what i am trying to do as i cant seem to find a solution anywhere.

    what i have is several sub-categories under a main category. but the second tier categories are not child categories of the main. only the sub categories under the second tier are child. but i still want to contain the loop of those categories on the main category, but essentially it will never have a post nor a child. I managed to find the filter to display a loop of the categories below it, but the page only appears if there is one post in that category…

    LOL, this all sound rather complicated when i say it out loud haha… I hope you get what i am talking about.

    In short i want to have the category page displayed even without and posts under it. I am using a custom theme and template files for each category.

    Hope someone has the answer. :)

    Cheers

    • wpbeginner

      @robolist What’s the point of having a category with no post under it? It seems like it shouldn’t even be there. Perhaps you want to elaborate, so we can see what you are doing with that category. Maybe an alternative route should be taken.

      • robolist

        @wpbeginner thanks for getting back so fast :)

        ok so the reason is because i dont want the main category to appear in the URL structure. although the final URL for the post will be different. The main category will be something like 'destinations’ then under that will have countries. with each country having a child city then posts under the city. so the main menu will display 'destinations’ with a loop of all posts under that. then under that in the sub menu will be the country then city. with both country and city containing a loop of its respective posts.so by the time you get to the city landing page i dont want the URL to be ’.com/destinations/country/city/ ’ i want it to be ’.com/country/city/’

        You see my dilemma?

        • wpbeginner

          @robolist It seems like there is a better way.Wouldn’t it make more sense to eliminate destination category altogether. Create a page called Destinations – use custom page template to have it output all categories that WordPress has using wp_list_categories() function. Now you will still have the urls like .com/country/city/And when the user goes on a page like .com/destinations/ << They can still see all the countries listed there. Does that make sense? If it doesn’t, then maybe we don’t understand what you are trying to do.

        • robolist

          @wpbeginner that does sound better and makes sense… But i am not familiar with the wp_list_categories() function, although i have seen it around. This could be the one. thanks so much for your help, i will go and give that a try :) thanks so much…

          thanks also for all your amazing tutorials on this site…

        • wpbeginner

          @robolist wp_list_categories() is a very simple and powerful function. http://codex.wordpress.org/Template_Tags/wp_list_categoriesIt will let you display your categories anywhere in a custom page template. https://www.wpbeginner.com/wp-themes/how-to-create-a-custom-page-in-wordpress/ So create a custom page template. In the template area paste the codewp_list_categories(); Make sure to set child=0 if you don’t want to show your cities in there. As I presume, you will only want to display the countries there. Then once a user clicks on a country, they go and see all the cities. Style it to your liking and there you have it.

        • robolist

          @wpbeginner excellent :) thanks so much

        • robolist

          @wpbeginner

          hey guys, thanks so much for your advice last night, it worked a treat :). I am however stuck on the permalink structure now and would be very grateful if you and any tips for me again :)

          My final post is now at the end of a three tier category structure, 'continent/country/city/post/’ (destinations as you recommended is now a page). But for the final URL of the post i dont want it to be four deep and would prefer it to only be three deep. so the permalink that i would like is country/city/post/… Is there anyway i can remove the top level parent category from the permalink structure? at the moment i have it set up like this '/%category%/%postname%-%post_id%/’ But it automatically grabs all parent categories. , Do i have to again make the top category a page or is there a better way round this? Many thanks in advance for your help

          Cheers

        • wpbeginner

          @robolist You can write some permalink rewrite rules, but that is a bit harder than making the top category a page. Easy solution: make continent a page.Hard solution: rewrite permalink rule.Honestly, do you need continents? most folks don’t really look by North America or South America… They just look for countries…

        • robolist

          @wpbeginner Thanks for getting back to me.

          Well having the continents does help to organise the blog as it will get pretty big eventually, its more like regions really, not exactly continents, which is why I’d prefer to include them . I would love to learn how to do the rewrite rule because that way i wont have to be constantly adding extra category IDs to the region pages every time a new city/country is added. The way i have it set with the destinations is perfect because i will never add any more regions so i never have to touch that page again,:) as it stands there are 9 regions thats it., but countries and cities will be added over time

          i dont suppose you could point me in the right direction for the rewrite? :) I would be ever so grateful

          Many thanks for all your help so far

        • wpbeginner

          @robolist Rewrite requires writing custom codes and which is something we charge for. You can look at google for your guide or look in the WordPress core if you like tackling code.

        • robolist

          @wpbeginner I would love to hire you guys but just dont have a budget for that :(, plus i would love to learn how to do it myself. but thanks so much for all the help you have given me on this. if i do fail at my attempt then i will just go for the simple way out and create pages for the regions. thanks again :)

  29. sdiggles

    Did you ever get this? I am trying to accomplish the same thing right now. Only show subcategories on category pages if there are subcategories. That „No categories” stuff is killing me.

    • robolist

      @sdiggles i think i am after the same… did you find a solution?

  30. Seosphere

    Hi ! sorry for my english.

    I would like to use your code, but not on the sidebar. When i click on a main category, i would like to find on the nav. bar the sub menu instead to have the main menu.

    Sorry but i m not a developper, where do i have to paste your code ?

    In category.php ? :(

    Thank you

  31. Aleksandr

    The code is not finished.

    «…
    if ($this_category) {
    //There is must be a code
    //to show the list of subcategories.
    }?>
    …»

    Something like that:
    if ($this_category) {
    printf( $this_category );
    }

    P.S. working on «Twenty Ten» 3.0.1

  32. tes

    testing with v 3.0 doesnot work.. buggy

  33. Emily

    I’ve heard that this code no longer works since the WP upgrade. I also got a parse error.

  34. Rachel

    Hi,
    This code is exactly what I need, only I want to use it in the actual category.php content section, not in the sidebar. Anyway, I pasted it in and I get a parse error. Is there something missing at the end of the code snippet?
    Thanks.
    -Rachel

    • Editorial Staff

      So many things can matter. Where exactly did you place it… please contact us via our contact form for help.

      Administrator

    • David

      Rachel, did you get this figured out? I’m getting the same error.

  35. Karl B

    This is a great starting point for me as I had been searching high and low for this.

    I wondered if there was a way to elaborate on this and allow say, 1 post title and excerpt then 4 more titles from each subcategory, displayed in a div.

    I have been trying to find a way to do this for months but have never found anyone able to assist. I even offered a small payment but no-one came forward :)

    Thanks if anyone can offer any advice :)

    Karl

    • Editorial Staff

      We can help you if you contact via email. There is a way to do it that can be explained either via email, or we can do it for you for a small payment :)

      Administrator

  36. Jerry

    I’m getting a „Parse error: syntax error, unexpected '='” error from this?

    Ideas?

    • Editorial Staff

      Try it now :) It should work. The code just converted the quotes into curly quotes.

      Administrator

  37. Jacqueline

    Hi, thanks so much for this code and I have it working on my template. How would I prevent this entire code from running if a category has NO children? If there are no children, it creates an empty list and prints the text „No Categories.” Here’s how I had it setup with Yoast’s code:

    cat_ID) != „”) { ?>

    Subcategories:
    cat_ID);?>



    If there were no subcategories, nothing would show up. Your code is better, but I need it to only show up ONLY if there are subcategories. How would I achieve this? Thanks for any suggestions.

  38. Victor

    Thanks for posting this. I got my posts displaying fine, but had forgotten about the sub cats…it makes more sense this way.

  39. Nick

    Hi,

    I’m trying to accomplish this in the sidebar, only instead of links, I want to list recent posts in subcategories.

    and of course, this would occur in all category and subcategory pages, as well as single posts.

    Don’t know if this is possible. But, I’ve been looking around like crazy, and not being a programmer isn’t helping either.

Zostaw odpowiedź

Dziękujemy za pozostawienie komentarza. Pamiętaj, że wszystkie komentarze są moderowane zgodnie z naszymi polityka komentarzy, a Twój adres e-mail NIE zostanie opublikowany. NIE używaj słów kluczowych w polu nazwy. Przeprowadźmy osobistą i konstruktywną rozmowę.