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 skapar du customize templates för enskilda inlägg i WordPress

En av våra läsare frågade oss hur man skapar templates för enskilda inlägg i WordPress.

Vi på WPBeginner har hjälpt många website-ägare att förbättra sina blogginlägg med unika layouts för enskilda posts. Custom single-post templates allow you to use different designs for your blog posts, giving each one a distinct look. Många WordPress teman erbjuder några page templates, men du kan också skapa dina egna om det behövs.

I den här artikeln visar vi dig flera metoder för att enkelt skapa mallar för enskilda inlägg i WordPress, så att du kan välja den som fungerar bäst för dina behov.

How to Create Custom Single Post Templates in WordPress

När behöver du en Custom Template för enskilda inlägg?

Ibland vill du kanske ha ett annat utseende för vissa posts på din website i WordPress. You kanske till exempel vill använda en annan layout för utvalda artiklar eller stories i en viss kategori.

Det är här du behöver en customized template för enskilda inlägg i WordPress.

Som standard använder WordPress mallen för enskilda inlägg baserat på WordPress mall-hierarki. Alla teman levereras med en single.php template, och den används som standard för alla dina enskilda inlägg.

Vissa teman kan också innehålla ytterligare templates eller val av layout som du kan använda.

Det är ungefär som att skapa en custom page template. De flesta WordPress teman kommer också med sidmallar som du kan använda när du redigerar ett post eller en page i WordPress.

Choosing a Page Template

Med detta sagt, låt oss ta en titt på hur man enkelt skapar customize templates för enskilda inlägg i WordPress. Vi kommer att visa dig flera metoder, så att du kan använda den som fungerar bäst för dig.

Skapa templates för enskilda inlägg med hjälp av Block Editor

Den här metoden skapar ej riktigt en template för ett post och är limit i flexibilitet. Det är dock det enklaste sättet att save dina egna layouts för enskilda inlägg och sedan återanvända dem.

Standard WordPress Block Editor kommer med en built-in funktion som allow you att save och återanvända block. Ett sådant återanvändbart block är gruppblocket.

Med gruppblocket allow you att lägga flera block och hela post layouts i en grupp. Du kan sedan save detta group block och återanvända det i dina andra posts.

Låt oss ta en titt på hur du använder gruppblocket för att save your custom post templates.

Först måste du skapa en new post i WordPress. Därefter lägger du helt enkelt till ett gruppblock i innehållsområdet.

Add Group Block

Nu kan du börja lägga till block i gruppblocket för att skapa en layout för ett enskilt inlägg för din WordPress blogg.

You can add to any blocks you want, including columns, media and text, cover images, and more.

Add Blocks to the Group

När du är nöjd med den layout du har skapat måste du ta upp musen och selecta gruppblocket.

Klicka bara på den trepunktade ikonen i menyn och välj sedan alternativet ”Add to Reusable blocks”.

Add Reusable Block

Därefter måste du ange ett namn för det återanvändbara blocket och sedan klicka på knappen Save. WordPress sparar nu ditt återanvändbara block, inklusive alla block inom gruppblocket.

You can then edit any existing post on your website or create a new one. På vyn för edit av post klickar du bara på knappen add new block och letar efter ditt saved block under tabben ”Reusable”.

Reuse Block

Add blocket till din post, och WordPress hämtar hela ditt gruppblock med alla block och settings som du har saved dem.

Den här metoden allow you att save your custom layouts. Det saknar dock behörighet att ändra hur ditt theme hanterar enskilda inlägg.

Om du gillar större flexibilitet, fortsätt då att läsa nästa steg.

Skapa customize mallar för enskilda inlägg med hjälp av SeedProd

Det enklaste sättet att skapa en custom template för enskilda inlägg är att använda SeedProd. Det är det bästa WordPress plugin för webbplatsbyggare och kan skapa beautiful website layouts och customize templates utan att skriva någon kod.

Du kan använda SeedProd’s drag and drop-byggare för att skapa ett helt custom WordPress theme, inklusive templates för enskilda inlägg.

Det första du behöver göra är att installera och aktivera pluginet SeedProd. För mer detaljer, se vår Step-by-Step guide om hur du installerar ett WordPress plugin.

Vid aktivering måste du enter din license key. Du hittar denna information under your account på SeedProds website.

SeedProd license key

Efter det är det dags att skapa ett customize WordPress theme. Det här är mycket enklare än det låter.

Skapa ett Custom WordPress Theme

Först måste du heada över till SeedProd ” Theme Builder-sidan. Här kommer du att använda ett av SeedProds färdiga teman som utgångspunkt. Detta kommer att ersätta ditt befintliga WordPress theme med en new, customize design.

Du kan göra det genom att clicka på knappen ”Themes”.

Create your custom theme

You will be shown a list of professionally designed themes for different types of websites. Det finns till exempel templates som heter ”Modern Business”, ”Marketing Agency” och ”Mortgage Broker Theme”.

Ta en titt på alternativen och välj ett som bäst matchar dina behov genom att clicka på checkmark icon.

Select a Theme That Matches Your Needs

När du har valt ett tema kommer SeedProd att generera alla templates du behöver, inklusive en för enskilda pages och en annan för enskilda inlägg.

Varje template kommer med attraktiva layouts och placeholder content som är lätt att customize.

SeedProd Creates All the Templates You Need for Your Theme

För att lära dig mer om hur du skapar ett tema med SeedProd, se vår guide om hur du enkelt skapar ett customizer WordPress theme utan någon kod.

Customize standardmallen för enskilda inlägg

SeedProd gör det enkelt att customize standard ”Enskilt inlägg” template med hjälp av en drag and drop page builder.

Klicka bara på länken ”Edit Design” som finns under templates. Detta kommer att öppna din post template i SeedProd’s visual editor.

Click the 'Edit Design' Link Under the Single Post Template

SeedProd’s visual editor har en layout med 2 Column. Till vänster hittar du block och sections som du kan add to din design.

Till höger finns en preview av templates där du kan se dina ändringar i realtid.

SeedProd Visual Editor Blocks and Sections

Det är också enkelt att customize layouten i din post template. Klicka bara på ett block för att se dess inställningar i den vänstra colonnen.

Om du till exempel klickar på rubriken till ett post kan du se dess Settings. Nu kan du ändra justering, storlek på font, nivå på heading med mera.

Click on a Block to Change Its Settings

Om du klickar på tabben Advanced kan du ändra färger på font, avstånd och andra stilar.

Du kan add to ytterligare block genom att dra dem från den vänstra columnen till preview columnen. SeedProd använder malltaggar för att dra in dynamiskt content som gillar titlar på inlägg, featured images, comments, och mer. Detta låter dig add to content till templates utan att behöva edit varje post individuellt.

Till exempel kan du add to a Posts block at the end of your post content. Detta kommer att visa senaste inlägg som dina besökare kanske vill läsa när de slutför det aktuella inlägget. Detta block visas automatiskt på alla posts som använder denna template.

Add a Posts Block to the Bottom of Your Single Posts Template

Därefter kan du ändra inställningarna för blocket Posts för att customize det content som visas.

Du kan till exempel visa content från specifika kategorier, använda en layout med två Column och ändra antalet posts som visas.

SeedProd Posts Block Settings

Lägg gärna tid på att experimentera med olika block och utforska deras Settings.

När du har skapat något som du gillar att använda som din post template, är det dags att spara det genom att klicka på den gröna ”Save” knappen i det övre högra hörnet. Efter det kan du stänga SeedProd visual editor genom att clicka på ’X’ close icon.

When You're Finished, Save the Single Post Template

Du kan customize resten av ditt WordPress theme på samma sätt. Men om du behöver lite hjälp kan du gå tillbaka till vår Step-by-Step guide om hur du skapar ett customize WordPress Theme med SeedProd.

När du är nöjd med hur allt ser ut, se till att ”Aktivera SeedProd Theme”-omkopplaren är togglad till positionen on. Din WordPress site kommer nu att använda ditt SeedProd theme och din custom template för enskilda inlägg.

Enable the SeedProd Theme

Använda Theme Settings för att skapa customize layouts för enskilda inlägg

Många populära WordPress teman kommer med built-in settings för att customize utseendet på din template för enskilda inlägg.

Om ditt theme har support för dessa settings kommer du att kunna hitta dem på vyn för post-edit. De tillgängliga alternativen kan ändras beroende på vilket theme du använder.

Till exempel erbjuder Astra theme alternativ för customize när du redigerar ett enskilt inlägg. Med hjälp av dessa alternativ kan du ändra sidebar, dölja rubriker, rubriker, menyer och mer.

Astra Theme Single Post Template Customization

Å andra sidan kommer många av de högst upp WordPress teman med färdiga templates som du kan använda.

Om ditt theme innehåller templates för enskilda inlägg hittar du dem under panelen ’Template’ eller ’Post Attributes’ när du redigerar ett inlägg.

Choosing a Template When Writing a Single Post

Dessa templates är kompletta layouts som du kan använda utan att det är obligatoriskt att konfigurera dem.

Skapa manuellt anpassade mallar för enskilda inlägg med kod

Den här metoden är lite avancerad eftersom den kräver att du redigerar temafiler, copy and paste-kod och valfritt lägger till custom CSS. Om du inte har gjort detta tidigare, kontrollera vår tutorial om hur du kopierar och klistrar in kod i WordPress.

Först måste du öppna en plain text editor på din dator som Notepad och klistra in följande kod i den:

<?php
/*
 * Template Name: Featured Article
 * Template Post Type: post, page, product
 */
  
 get_header();  ?>

Denna code type definierar en new template som anropas ”Featured Article” och gör den available för post, page och product post types.

Du bör save denna fil som wpb-single-post.php på your desktop. Därefter måste du add to templates till din WordPress site. För att göra det måste du använda en FTP-klient för att uploada filen till din aktuella theme folder.

Nu kan du logga in på din WordPress admin area och skapa eller editera ett post. Rulla ner lite på vyn för redigering av inlägg, så kommer du att notera en new ”Template” panel eller ”Post Attributes” meta box med ett alternativ för att välja mall.

Select Your Custom Post Template

Du kommer att se din ”Featured Article” custom template listad där.

Just nu är din template i princip tom, så när du väljer den visas helt enkelt en vit vy.

Nu fixar vi det här.

Det enklaste sättet att göra det är genom att kopiera koden från ditt temas single.php-fil och använda den som utgångspunkt. Du måste öppna filen single.php och sedan kopiera allt efter get_header( )-raden.

Därefter måste du klistra in den här koden i slutet av din wpb-single-post.php-fil. Nu kan du save filen och uploada den tillbaka till din server.

Detta kommer dock att se exakt likadant ut som din nuvarande template för enskilda inlägg. Du kan nu börja göra ändringar i din customze-mall för enskilda inlägg.

You can add to your own custom CSS classes, remove sidebars, create a full width template, or anything you want.

Skapa customize mallar för enskilda inlägg efter Category

Gillar du att använda en custom template för enskilda inlägg baserat på kategorier? Du kan t.ex. ge posterna i kategorin resor en annan layout än posterna i kategorin fotografier.

Du kan göra det med hjälp av antingen SeedProd Theme Builder eller kod.

Skapa Customize mallar för enskilda inlägg efter Category med SeedProd

Tidigare har vi täckt hur man customize SeedProd Theme Builder’s standard mall för enskilda inlägg. Men det stannar inte där. Med SeedProd kan du add to så många custom post-mallar som du gillar, till exempel en annan layout för varje post-kategori.

För att add a new single post template, just click the ’Duplicate’ link under den ursprungliga post template. En new template som anropas ”Single Post – Copy” kommer att skapas och läggas till högst upp på temats templates page.

Create a New Post Template by Duplicating the Default Post Template

Du kan customize den nya mallen på samma sätt som du customizade standard mallen för enskilt inlägg tidigare. Klicka bara på template’s ”Edit Design” link och gör de ändringar du gillar med SeedProd’s visual editor.

När du har slutfört customize mallen, måste du add to några villkor så att SeedProd vet vilka posts som ska använda denna template. I det här fallet vill vi att den ska visas när vi viewar inlägg inom en enskild kategori.

Click the 'Edit Conditions' Link

Du kan göra det genom att clicka på templatens ”Edit Conditions” link och ett new fönster kommer att dyka upp.

Här kan du ge templates ett namn och en prioritet. Standardmallen för enskilda inlägg har en prioritet på 0, så se till att du ger den här mallen en högre prioritet så att den visas i matchande kategorier.

Add Conditions to Display the Template for a Certain Category

Under ”Villkor” väljer du ”Har kategori” i den andra rullgardinsmenyn och skriver sedan namnet på kategorin i det sista fältet. Om du till exempel bara vill att posts från kategorin fotografering ska använda den här layouten skriver du ”fotografering”.

När du är slutförd klickar du på knappen ”Save” och nu kommer den här templaten att användas för alla posts i den matchande kategorin.

Detta är det enklaste sättet att skapa flera custom post templates i WordPress. Det kräver ingen kunskap om kod och kommer inte av misstag att röra upp några theme-filer.

Skapa customize mallar för enskilda inlägg efter kategori med hjälp av kod

Detta är en annan metod för dem som är bekväma med att lägga till kod i sina theme-filer.

Först måste du add to den här koden till functions.php-filen i ditt theme eller till ett code snippets plugin.

/*
* Define a constant path to our single template folder
*/
define(SINGLE_PATH, TEMPLATEPATH . '/single');
 
/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_template');
 
/**
* Single template function which will choose our template
*/
function my_single_template($single) {
global $wp_query, $post;
 
/**
* Checks for single template by category
* Check by category slug and ID
*/
foreach((array)get_the_category() as $cat) :
 
if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';
 
elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';
 
endforeach;
}

Den här koden kontrollerar först om WordPress requestar ett enskilt inlägg. Om så är fallet säger den till WordPress att leta efter templates i /single/ foldern i your WordPress theme.

Nu måste du add to template-filer som definieras av den här koden.

Anslut till ditt WordPress webbhotell med hjälp av en FTP-klient eller File Manager i cPanel och gå till /wp-content/themes/your-theme-folder/.

I din nuvarande theme-mapp måste du skapa en new folder som heter ”single”. Därefter måste du öppna den här mappen och skapa en new fil. Gå vidare och namnge den här filen single-cat-{category-slug}. Ersätt {category-slug} med din faktiska kategori-slug.

Om du till exempel har en kategori som heter ”News”, skapar du filen single-cat-news.php. Om du har en kategori som heter ”Restips”, skapar du en template single-cat-travel-tips.php, och så vidare.

Creating Single Post Template for Categories

Nu kommer dessa templates filer att vara helt tomma. Som en utgångspunkt kan du kopiera innehållet i din single.php-fil från din theme folder och klistra in dem i var och en av dessa templates. Efter det måste du editera dessa templates för att göra dina önskade ändringar.

När du är klar kan du gå till din website och viewa ett post. Den kommer att använda den template som du har skapat för den kategori där detta post är arkiverat.

Låt oss nu anta att du har en post som är arkiverad i två kategorier: New: och Restips. WordPress kommer automatiskt att visa templates för ”News” eftersom den visas först i alfabetisk order.

Å andra sidan, om du arkiverade ett inlägg i en kategori och inte skapade en mall för den kategorin, kommer WordPress att falla tillbaka till standard single.php template i ditt theme.

Skapa Custom Mallar för enskilda inlägg för specifika författare

Låt oss anta att du vill att posts skrivna av en viss författare ska se annorlunda ut på din website. Det kan du göra med hjälp av kod genom att följa samma teknik som vi visade för kategorier.

Först måste du add to den här koden till functions.php-filen i ditt theme eller till ett code snippets plugin.

/**
* Define a constant path to our single template folder
*/
define(SINGLE_PATH, TEMPLATEPATH . '/single');
 
/**
* Filter the single_template with our custom function
*/
add_filter('single_template', 'my_single_author_template');
 
/**
* Single template function which will choose our template
*/
function my_single_author_template($single) {
global $wp_query, $post;
 
/**
* Checks for single template by author
* Check by user nicename and ID
*/
$curauth = get_userdata($wp_query->post->post_author);
 
if(file_exists(SINGLE_PATH . '/single-author-' . $curauth->user_nicename . '.php'))
return SINGLE_PATH . '/single-author-' . $curauth->user_nicename . '.php';
 
elseif(file_exists(SINGLE_PATH . '/single-author-' . $curauth->ID . '.php'))
return SINGLE_PATH . '/single-author-' . $curauth->ID . '.php';
 
}

Därefter ska du ansluta till din website med FTP eller cPanel filhanterare i cPanel och sedan gå till /wp-content/themes/your-theme-folder/. Om du inte redan har skapat en folder som heter /single/ inuti den, gå då vidare och skapa den nu.

I den här foldern måste du skapa en template som använder författarens användarnamn i templatesnamnet. Till exempel, single-author-johnsmith.php.

Denna template kommer att vara tom, så du kan copy and paste innehållet i ditt temas single.php template och använda den som utgångspunkt.

You kan nu besöka your website för att viewa ett post som skapats av en specifik författare. Det kommer att använda den template som du skapade.

Vi hoppas att den här artikeln hjälpte dig att lära dig hur du skapar customize templates för enskilda inlägg i WordPress. Du kanske också vill lära dig hur du trackar webbplatsens besökare till din WordPress site, eller se vår lista över måste ha WordPress tillägg för att växa din website.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Avslöjande: Vårt innehåll stöds av våra läsare. Det innebär att om du klickar på några av våra länkar, kan vi tjäna en provision. Se hur WPBeginner finansieras, varför det är viktigt, och hur du kan stödja oss. Här är vår editoriala process.

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Den ultimata WordPress-verktygslådan

Få GRATIS tillgång till vår verktygslåda - en samling WordPress-relaterade produkter och resurser som varje professionell användare bör ha!

Reader Interactions

70 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. Jasmine says

    I am getting this message when I try to use the code:

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ’my_single_template’ not found or invalid function name.

    Any ideas as to why?

  3. Iulian says

    All good but it breaks the default single.php.

    In other words this ”On the other hand, if you filed a post in a category and didn’t create a template for that category, then WordPress will fallback to the default single.php template of your theme.” is not working.

    Any solution?

  4. Thomas says

    Hi, I am trying to follow the step:
    Open the single.php file and then copy everything after the get_header() line.
    Under:
    Manually Creating Custom Single Post Templates in WordPress
    However, I don’t have any ”get_header()” function in that file.

    • WPBeginner Support says

      Your specific theme may have some unique coding, we would recommend reaching out to the support for your specific theme and they should be able to assist.

      Administratör

  5. bob says

    Thanks for this. All my auto generated files (author, not found etc) are using my site template then putting a white section with white text on thepage. its also starting at the top of the page (so its white text on a white background mostly hidden behind a page header)

    I believe your article will help me sort this mess out.

    Thank you

    • WPBeginner Support says

      Our article should help and if you reach out to your theme’s support they may be able to assist as well :)

      Administratör

    • WPBeginner Support says

      The templates should still be found under the top right section in the content panel

      Administratör

  6. John says

    Am I correct in thinking that once you create a custom post template php file, for it to work as a template, you still need to code the php file, as there is no way to save a new post as a template. Is this correct?

    Thank you for your help.

    • WPBeginner Support says

      That is correct, for changing the template unless you are using a page builder there is not a method to set it up without coding.

      Administratör

  7. Haripal Reddy says

    Hello Author,

    I followed the steps as you mentioned. I have CPT albums. single-albums.php copied same code to other file wpb-single-albums.php and added template code like /*
    * Template Name: custom template
    * Template Post Type: albums
    */
    and changed some required changes. But after selecting this template in edit post but it displays default one (single-albums.php) page.

    How can i fix this please help

    • WPBeginner Support says

      You may want to check the current working template to ensure you have the post type correct

      Administratör

  8. Alice says

    Thanks for your great post. I have 2 questions: Are single post templates the same with custom post type templates? If the are different, can you show me how to create a custom post type template?

  9. aziz says

    hello
    than you for the post
    i did everything and worked like i wanted.
    but i had a small problem
    after adding the code to function.php single.php stopped showing data
    is there anything i can do?

  10. Binesh says

    Hi, Thanks for your Tutorial…

    As per your tutorial I have created a custom Post type. But now I am facing an issue with comment. While submitting the comment it redirected to search…
    Pls suggest a solution for this..
    Thanks in Advance

  11. Mike says

    Hello.

    I’m using this & enjoying it greatly! :)
    However, I’m finding the following warning in my error logs around this code:

    [warn] mod_fcgid: stderr: PHP Warning: Use of undefined constant SINGLE_PATH – assumed ’SINGLE_PATH’ (this will throw an Error in a future version of PHP)

    Any thoughts on how to fix that?

    Your snippet starts with ”define(SINGLE_PATH,…” so I’m not sure what else to do here.

    • WPBeginner Support says

      That error is saying it wants SINGLE_PATH to be surrounded by single quotes (”) which you can do for that warning :)

      Administratör

  12. Jojo says

    So I followed your steps and its working for the new category slug single page but not for the default single.php.

    How can I get this to work? Perhaps the default single.php path is wrong?

    Thanks!

  13. Hil says

    Hi,

    I am overthinking this but…if I want every blog post to look the same, do I just create the Layout (I use Divi theme), use the above first method (make a new version of single.php named properly) and choose that every time I want to create a post? That simple?

    Also, to add the custom CSS, do you add to the php file, and how? Where within it do you add it? How should it look? That’s the part that I haven’t yet found any reference on how to do. Can you do an example based on just having every blog post look one way?

    Thank

  14. Malgorzata says

    Hi, thanks dfor great tutoriasl. It is working amazing but not for new categories, which doesnt have special template. Unfortunatley it is not getting the code from default single.php file. I will appreciate some help how to make it work.

  15. STEVE says

    Hi, Thanks for the tutorial!

    I have a question. How would we apply custom CSS that would only effect the Posts pages?

    Thanks

  16. TRAVIS says

    What if you want to make your new template the default for everything. So that anytime a post is created it is automatically selected as the default template?

  17. Jae says

    I bet there are plugins that you can use to do the job without the hassle of coding and child themes. It would’ve been great if you’d researched and shared that in this post too.

  18. peyman says

    I use your method but I can’t set custom css for this posts.
    for example in function.php when I check is_page_template(’single-cat-news’) the statement not getting true and my custom css for this kind of post not running. what should I do in this case?

    • Bikram says

      True.
      I’m also having this problem. The full-width template works well for post and pages but when it comes to custom post type, the CSS codes don’t work and goes back to normal page size without a sidebar.
      I’m having a hard time finding a solution to that problem.

  19. Mike says

    Need some additional help with this…

    Following the instructions on this page (along with the small modifications noted within my comments on 12/2/17 and 12/12/17), I’ve been able to get this working reliably.

    HOWEVER, I’ve run into the issue where using this method to call a custom template does not seem to get registered with the call of body_class classes.

    For example, if I set a custom template on a page (where I’m using WordPress’ ”Template” drop-down within the ”Page Attributes” sidebar in the editing view – then the body_classes that are output would include that template name.

    Such as:

    <body class="page-template-my_custom_template page page-id-2..."

    But, using this method, the body classes just return:

    <body class="page-template-default page page-id-2..."

    Any idea on how to ensure the body classes reflect a custom single post template?

    • Mike says

      Here’s the answer (for my theme, at least – your experience may vary).

      Adding the following to [b]functions.php[/b] did the trick for me:

      add_filter('body_class','add_category_to_single');
        function add_category_to_single($classes) {
          if (is_single() ) {
            global $post;
            foreach((get_the_category($post->ID)) as $category) {
              // add category slug to the $classes array, starting with 'category-'...
              $classes[] = "category-$category->category_nicename";
            }
          }
          // return the $classes array
          return $classes;
        }
      
  20. Dzungx Corn says

    I created a single-cat-news.php file for ”News”. My ”News” category has two child: ”Camera” and ”Smartphone”. The post in ”Smartphone” display in single-cat-news.php (S after N in alphabet), but the post in ”Camera” display in default single.php (C before N in alphabet). I want post in ”Camera” display in single-cat-news.php, what must I do? I selected both ”News” and ”Camera” for my post.

  21. Sarmad Gardezi says

    Im viewing your Blog from last 2 years. I explored whole web to find this but i got the correct working code from here i just love your Blog keep it up :)

  22. Mike says

    When using this approach to specify a custom post template for a single post within a specific category, I was finding that WordPress was NOT defaulting back to single.php in instances where a single-cat-WHATEVER.php file didn’t exist for a specific category.

    I fixed this by adding the following line before the end of the function:

    else
    return SINGLE_PATH . '/single.php';

    So that, this code:


    /**
    * Checks for single template by category
    * Check by category slug and ID
    */
    foreach((array)get_the_category() as $cat) :

    if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

    elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';

    endforeach;
    }

    Became this:


    /**
    * Checks for single template by category
    * Check by category slug and ID
    */
    foreach((array)get_the_category() as $cat) :

    if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php';

    elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'))
    return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php';

    else
    return SINGLE_PATH . '/single.php';

    endforeach;
    }

    Does this seem like the right approach? Or, is there something else that I may have done to break the default functionality?

  23. Mike says

    Thank you for this clear ’how to.’

    One note: for those of us using a CHILD THEME, I’ve found that changing…

    define(SINGLE_PATH, TEMPLATEPATH . ’/single’);

    to:

    define(SINGLE_PATH, get_stylesheet_directory() . ’/single’);

    (within the ”Define a constant path to our single template folder” section) ensures that child theme’s directory is checked for single templates instead of the parent theme’s directory.

    This may also be the reason that it’s not working for some of the other commenters above.

    Good luck, everyone!

    • Stephanie Lewis says

      Thank you so much for your help! I was wondering why it kept pointing me back to the parent theme instead of the child theme.

  24. Olayinka says

    Thank you for this article.
    I will want to know how I can further customise the layout of this single custom post template, like placing an image in the post before the content and in the footer.

  25. oussama says

    Hi,
    I need to change the order of 3 things in the post page which they are in the bottom of the article:
    1-a pagination plugin.
    2-an ad.
    3-social share icons.

    I want to make them in the following order (vertically):
    1-the ad
    2-the social share icons
    3-the pagination plugin

    How can I do that please?

  26. Linda Holiner says

    Thank you for your great tutorials. I am having trouble with this one. I added the code to my functions.php but I’m not getting the single post template. Do I need to make a call to the function or does WordPress do that? Is there some way I can debug the function?

    I just want posts of a particular category to display differently when you link to them.

  27. Taufiq Mahmud says

    I wanted to make a custom post page where registered user of my site can able to post without using wordpress’s default post.php

  28. Pierrick says

    Hi! Thank you for this tutorial, but I’m quite new to web design and I started creating a whole wordpress theme. Everything works fine on my website, but I am trying to make it possible to add pages that all use a template I created, (like the page of a product in a catalogue) but I have no idea how to do that. I first tried to do so by creating a page template in which I put loops that display the content of an article or a page, such as its title, its text and the values of some custom fields. To do so I used a query_posts, but it requires to put the post’s or page’s id with ”page_id=” or ”p=”, which means the template is for one specific page, and I would have to create a template for each new page I add to this catalogue , and precising the id of the page/post manually in it, while what I wanted was to create a single template for all the pages of the catalogue…
    So while doing my research to find a solution, I found your article, and I tried to create a post using the new single post template, but no matter which template I select in the list, when I go to the url of the post it displays my home page… I’m probably doing everything wrong, and I’m not even sure I understood what a single post is and if it’s really what I need… I would really appreciate it if you could give me some clues on what I should do to solve my problem, or if there’s some tutorial somewhere that could help me…
    Thank you,

    Pierrick.

    • WPBeginner Support says

      Hi Pierrick,

      We are not sure we understand your problem completely. However, if you just want to create a template to be used by any page then custom page template is the right approach. Since you want users to be able to see any page, this means you don’t need to use query_posts, your loop will begin with the standard

      <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
      //
      		// Post Content here
      		//
      	} // end while
      } // end if
      ?>
      

      Administratör

  29. alex says

    Hi,

    I have a local setup with WP 3.7.x and Template Post Type: post, page, product is not available.

    How can i create seperate caterory php files for each post category???

    single-{slug}.php
    category-{slug}.php

    all doesn’t seem to work

    Any tips?

  30. Mark says

    I have set this up to work with categories, however when I select a post that does not have a category it fails to pick up the default template and does not display the post. I suspect my theme may be at fault. How would I hard code the single.php in the parent directory as the default to use if no category template exists ?

    Works perfectly if I copy the single.php into the /single/single-cat-name.php file but I don’t want 40+ duplicate files.

    • Eric Besso says

      first copy single.php to the /single folder

      then include this code right before the endforeach;

      else

      return SINGLE_PATH . ’/single.php’;

  31. Lyssie says

    This is exactly what I was looking for, thank you for spelling this out so simply! It leaves me with a question though: I removed my sidebar but now there’s just an empty space where it used to be. How can I stretch the main content section to cover the entire space? Thanks again!

    • WPBeginner Support says

      Hi Lyssie,

      That’s because your theme has defined content area width relative to the sidebar. You need to use inspect tool to find out which CSS class your conntent-area uses and then adjust by adding custom CSS to make it full width.

      .page-template-full-width .content-area {
          width: 100%;
          margin: 0px;
          border: 0px;
          padding: 0px;
      }
      
      .page-template-full-width .site {
      margin:0px;
      }
      

      Please see our guide on how to create full width page in wordpress

      Administratör

      • Lyssie says

        Thanks for the fast response! This was very helpful! Now, if I see:
        div id=”primary” class=”content-area”>

        when I use the inspect tool, which is the class my content area uses?

        • Lyssie says

          Oops, that didn’t come out right.
          div id=”primary” class=”content-area”
          main id=”main” class=”site-main” role=”main”

          article id=”post-4773″ class=”post-4773 post type-post status-draft format-standard hentry category-travel-2″
          div id=”featured-image”
          /div

  32. Joe Yee says

    That’s a great article and should helps a no-coder person like me. Customization of template would be something scary that you might break the theme altogether. Do you recommend make the custom template on a child theme or is it okay to do it right on the theme. Thanks a bunch.

    • WPBeginner Support says

      Hi Joe,

      You will not be changing any of your theme’s existing files. Instead, you will be creating a new file. If anything goes wrong you can simply delete the template and your site will be back to normal.

      Yes creating a child theme is the recommended best practice.

      Administratör

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.