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

WordPressでカスタマイザー個別投稿テンプレートを作成する方法

ある読者から、WordPressでカスタム個別投稿テンプレートを作成する方法を尋ねられました。

WPBeginnerでは、多くのサイトオーナーのブログを、個々の投稿のためのユニークなレイアウトで強化するお手伝いをしてきました。カスタム個別投稿テンプレートを使用すると、ブログ投稿に異なるデザインを使用することができ、それぞれの投稿に独特の外観を与えることができます。多くのWordPressテーマにはいくつかのページテンプレートが用意されていますが、必要に応じて自分で作成することもできます。

この投稿では、WordPressでカスタマイザー個別投稿テンプレートを簡単に作成するための複数の方法を紹介するので、あなたのニーズに最適なものを選んでほしい。

How to Create Custom Single Post Templates in WordPress

カスタマイザー個別投稿テンプレートはいつ必要ですか?

WordPressサイトの特定の投稿に対して、異なるルック&フィールを使いたい場合があります。例えば、特集記事や特定のカテゴリーの投稿に対して異なるレイアウトを使用したい場合があります。

そこでWordPressのカスタム個別投稿テンプレートが必要になる。

初期設定では、WordPressはWordPressのテンプレート階層に基づいた個別投稿テンプレートを使用します。すべてのテーマにはsingle.phpテンプレートが付属しており、初期設定ではこれがすべての個別投稿に使用されます。

テーマによっては、追加テンプレートやレイアウトの選択肢が含まれている場合もあります。

これはカスタマイザーでページを作成するのとよく似ている。ほとんどのWordPressテーマには、WordPressで投稿やページを編集する際に使用できるページテンプレートも付属しています。

Choosing a Page Template

それでは、WordPressでカスタム個別投稿テンプレートを簡単に作成する方法を見ていきましょう。複数の方法を紹介するので、自分に最適なものを使ってほしい。

ブロックエディターを使った個別投稿テンプレートの作成

この方法では投稿テンプレートは作成されず、柔軟性にも限界があります。しかし、個別投稿のレイアウトを保存して再利用する最も簡単な方法です。

初期設定のWordPressブロックエディターには、ブロックを保存して再利用できる機能がビルトインされています。そのような再利用可能なブロックの一つがグループブロックです。

グループブロックを使うと、複数のブロックや投稿レイアウト全体を1つのグループにまとめることができます。そして、このグループブロックを保存し、他の投稿で再利用することができます。

カスタム投稿テンプレートを保存するためにグループブロックを使用する方法を見てみましょう。

まず、WordPressで新規投稿を作成する必要があります。その後、コンテンツエリアにグループブロックを追加するだけです。

Add Group Block

これで、グループブロックにブロックを追加して、WordPressブログの個別投稿レイアウトを作成できるようになります。

カラム、メディア、テキスト、カバー画像など、お好きなブロックを追加できます。

Add Blocks to the Group

作成したレイアウトに満足したら、マウスを上に持っていき、グループブロックを選択します。

三点メニューアイコンをクリックし、「再利用ブロックに追加」オプションを選択するだけです。

Add Reusable Block

次に、再利用ブロックの名前を入力し、「保存」ボタンをクリックします。WordPressが再利用ブロックをグループブロック内のすべてのブロックを含めて保存します。

その後、サイト上の既存の投稿を編集したり、新しい投稿を作成したりすることができます。投稿編集画面で、新規ブロック追加ボタンをクリックし、「再利用ブロック」タブで保存したブロックを探します。

Reuse Block

投稿にブロックを追加すると、WordPressは保存したすべてのブロックと設定でグループブロックを読み込みます。

この方法でカスタムレイアウトを保存できます。しかし、テーマが個別投稿をどのように扱うかを変更する権限はありません。

より大きな柔軟性をお望みなら、次のステップにお進みください。

SeedProdを使用したカスタム個別投稿テンプレートの作成

カスタム個別投稿テンプレートを作成する最も簡単な方法は、SeedProdを使用することです。これは最高のWordPressウェブサイトビルダープラグインであり、コードを書くことなく美しいウェブサイトのレイアウトとカスタムテンプレートを作成することができます。

SeedProdのドラッグアンドドロップビルダーを使用すると、カスタム個別投稿テンプレートを含む完全にカスタムWordPressテーマを作成することができます。

最初に行う必要があるのは、SeedProdプラグインをインストールして有効化することです。詳細については、WordPressプラグインのインストール方法のステップバイステップガイドをご覧ください。

有効化した場合、ライセンスキーを入力する必要があります。この情報は、SeedProdサイトのお客様のアカウントの下にあります。

SeedProd license key

その後、カスタマイザーのWordPressテーマを作成します。これは想像以上に簡単だ。

カスタムWordPressテーマの作成

まず、SeedProd ” テーマビルダーのページに移動する必要があります。ここでは、SeedProdの既製テーマの1つを出発点として使用します。これにより、既存のWordPressテーマが新しいカスタムデザインに置き換えられます。

テーマ』ボタンをクリックすれば、それができる。

Create your custom theme

さまざまなタイプのサイト用にプロがデザインしたテーマのリストが表示されます。例えば、「Modern Business」、「Marketing Agency」、「Mortgage Broker Theme」というテーマがあります。

オプションをご覧いただき、チェックマークアイコンをクリックして、お客様のニーズに一致するものをお選びください。

Select a Theme That Matches Your Needs

テーマを選択すると、SeedProdは個別ページ用と個別投稿用を含む必要なテーマテンプレートをすべて生成します。

各テンプレートには、魅力的なレイアウトとカスタマイズが簡単なプレースホルダーコンテンツがセットアップされています。

SeedProd Creates All the Templates You Need for Your Theme

SeedProdでテーマを作成する方法についてさらに詳しく知りたい方は、コードなしで簡単にWordPressカスタムテーマを作成する方法のガイドをご覧ください。

初期設定の個別投稿テンプレートのカスタマイズ

SeedProdでは、ドラッグ&ドロップのページビルダーを使用して、初期設定の「個別投稿」テンプレートを簡単にカスタマイズすることができます。

テンプレートの下にある「デザインを編集」リンクをクリックするだけです。投稿テンプレートがSeedProdのビジュアルエディターで開きます。

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

SeedProdのビジュアルエディターは2カラムレイアウトです。左側には、デザインに追加できるブロックとセクションがあります。

右側にはテンプレートのプレビューが表示され、変更内容をリアルタイムで確認することができます。

SeedProd Visual Editor Blocks and Sections

投稿テンプレートのレイアウトをカスタマイズするのも簡単です。任意のブロックをクリックするだけで、左カラムにその設定が表示されます。

例えば、投稿タイトルをクリックすると、その設定が表示されます。ここで、配置、フォントサイズ、見出しレベルなどを変更することができます。

Click on a Block to Change Its Settings

詳細設定]タブをクリックすると、フォントの色や間隔、その他のスタイルを変更できます。

左カラムからプレビューカラムにドラッグすることでブロックを追加することができます。SeedProdは、投稿タイトル、アイキャッチ画像、コメントなどの動的コンテンツを取り込むためにテンプレートタグを使用します。これにより、各投稿を個別に編集することなく、テンプレートにコンテンツを追加することができます。

例えば、投稿コンテンツの最後にPostsブロックを追加することができます。これは、訪問者が現在の投稿を終えたときに読みたいと思うかもしれない最近の投稿を表示します。このブロックは、このテンプレートを使用しているすべての投稿に自動的に表示されます。

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

次に、投稿ブロックの設定を変更し、表示されるコンテンツをカスタムすることができます。

例えば、特定のカテゴリーからのコンテンツを表示したり、2カラムレイアウトを使用したり、表示する投稿数を変更したりすることができます。

SeedProd Posts Block Settings

いろいろなブロックを試してみたり、セッティングを試してみたりして、自由に時間を過ごしてください。

投稿テンプレートとして使用したいものを作成したら、右上にある緑色の「保存」ボタンをクリックして保存します。その後、’X’クローズアイコンをクリックしてSeedProdビジュアルエディターを閉じることができます。

When You're Finished, Save the Single Post Template

WordPressテーマの残りの部分も同じようにカスタマイズできます。しかし、少し助けが必要な場合は、SeedProdでカスタムWordPressテーマを作成する方法のステップバイステップガイドを参照してください。

すべての外観に満足したら、’SeedProdテーマを有効化’スイッチがオンになっていることを確認してください。これであなたのWordPressサイトはSeedProdテーマとカスタム個別投稿テンプレートを使用するようになります。

Enable the SeedProd Theme

テーマ設定を使ってカスタム個別投稿レイアウトを作成する

多くの人気WordPressテーマには、個別投稿テンプレートの外観をカスタマイズするための設定がビルトインされています。

お使いのテーマがこれらの設定をサポートしている場合は、投稿編集画面で見つけることができます。利用可能なオプションは、使用しているテーマによって変更される場合があります。

例えば、Astraテーマは個別投稿を編集する際にカスタマイズオプションを提供する。これらのオプションを使用すると、サイドバーを変更したり、ヘッダー、タイトル、メニューなどを非表示にしたりすることができます。

Astra Theme Single Post Template Customization

一方、多くのトップWordPressテーマには、すぐに使えるテンプレートが付属しています。

あなたのテーマに個別投稿テンプレートが含まれている場合、投稿の編集中に「Template」または「Post Attributes」パネルでテンプレートを見つけることができます。

Choosing a Template When Writing a Single Post

これらのテンプレートは、設定の必要なく使用できる完全なレイアウトです。

カスタム個別投稿テンプレートをコードで手動作成する

この方法は、テーマファイルを編集し、コードをコピー&ペーストし、オプションでカスタムCSSを追加する必要があるため、少し高度です。この方法を行ったことがない場合は、WordPressでコードをコピー&ペーストする方法についてのチュートリアルをご覧ください。

まず、コンピューター上でメモ帳のようなプレーンテキストエディターを開き、その中に以下のコードを貼り付ける必要がある:

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

このコードは’Featured Article’と呼ばれる新しいテンプレートを定義し、投稿、ページ、商品投稿タイプで利用できるようにします。

このファイルをwpb-single-post.phpとしてデスクトップに保存してください。次に、WordPressサイトにテンプレートを追加する必要があります。そのためには、FTPクライアントを使用して、現在のテーマフォルダーにファイルをアップロードする必要があります。

これで、WordPressの管理エリアにログインし、投稿を作成または編集することができます。投稿編集画面を少し下にスクロールすると、新しい「テンプレート」パネルまたは「投稿属性」メタボックスにテンプレートを選択するオプションがあることに気づくでしょう。

Select Your Custom Post Template

そこにあなたの「注目記事」カスタムテンプレートが表示されます。

現在、テンプレートは基本的に空なので、それを選択すると単に白い画面が表示されます。

これを解決しよう。

最も簡単な方法は、テーマのsingle.phpファイルからコードをコピーし、それを出発点として使用することです。single.phpファイルを開き、get_header()行以降をすべてコピーする必要があります。

次に、このコードをwpb-single-post.phpファイルの最後に貼り付けます。このファイルを保存し、サーバーにアップロードしてください。

しかし、これは現在の個別投稿テンプレートと全く同じに見えます。これでカスタム個別投稿テンプレートの変更を開始できます。

独自のカスタムCSSクラスを追加したり、サイドバーを削除したり、全幅のテンプレートを作成したり、何でもできます。

カテゴリー別カスタム個別投稿テンプレートの作成

カテゴリーに基づいたカスタマイザー個別投稿テンプレートを使いたいですか?例えば、旅行カテゴリの投稿と写真カテゴリの投稿に異なるレイアウトを与えることができます。

SeedProdテーマビルダーまたはコードのいずれかを使用して行うことができます。

SeedProdを使用したカテゴリー別カスタム個別投稿テンプレートの作成

先に、SeedProdTheme Builderのデフォルト個別投稿テンプレートのカスタマイズ方法を説明しました。しかし、それだけにとどまりません。SeedProdでは、投稿カテゴリーごとに異なるレイアウトなど、カスタム投稿テンプレートを好きなだけ追加することができます。

新規個別投稿テンプレートを追加するには、元の投稿テンプレートの下にある「Duplicate」リンクをクリックするだけです。個別投稿-コピー」という新しいテンプレートが作成され、テーマテンプレートページの一番上に追加されます。

Create a New Post Template by Duplicating the Default Post Template

初期設定の個別投稿テンプレートをカスタマイズしたのと同じ方法で、新しいテンプレートをカスタマイズすることができます。テンプレートの’デザインを編集’リンクをクリックし、SeedProdのビジュアルエディターを使って好きなように変更してください。

テンプレートのカスタマイザーが終わったら、SeedProdがどの投稿にこのテンプレートを使うべきかを知るために、いくつかの条件を追加する必要があります。この場合、個別カテゴリー内の投稿を表示するときに表示させたい。

Click the 'Edit Conditions' Link

テンプレートの「Edit Conditions」リンクをクリックすると、新しいウィンドウが表示されます。

ここで、テンプレートに名前と優先度を与えることができます。初期設定の個別投稿テンプレートの優先順位は0なので、このテンプレートに高い優先順位を与えて、一致するカテゴリーに表示されるようにしてください。

Add Conditions to Display the Template for a Certain Category

条件」で、2番目のドロップダウンメニューから「カテゴリーを持つ」を選択し、最後のフィールドにカテゴリー名を入力します。例えば、写真カテゴリーからの投稿にのみこのレイアウトを使用したい場合は、「photography」と入力します。

完了したら、「保存」ボタンをクリックしてください。このテンプレートは、一致するカテゴリー内のすべての投稿に使用されます。

これはWordPressで複数のカスタム投稿テンプレートを作成する最も簡単な方法です。コードの知識は必要なく、テーマファイルを誤って混乱させることもない。

カテゴリー別のカスタム個別投稿テンプレートをコードで作成する

これは、テーマファイルにコードを追加するのに慣れている人向けの方法だ。

まず、テーマのfunctions.phpファイルまたはコードスニペットプラグインにこのコードを追加する必要があります。

/*
* 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;
}

このコードはまず、WordPressが個別投稿をリクエストしているかどうかをチェックします。もしそうなら、WordPressテーマの/single/フォルダーにあるテンプレートを探すようにWordPressに伝えます。

次に、このコードで定義されたテンプレート・ファイルを追加する必要がある。

FTPクライアントまたはcPanelのファイルマネージャを使用してWordPressホスティングサービスに接続し、/wp-content/themes/your-theme-folder/に移動します。

現在のテーマフォルダーの中に、「single」という新しいフォルダーを作る必要があります。次に、このフォルダーを開き、新規ファイルを作成する必要があります。このファイルの名前をsingle-cat-{category-slug}とします。category-slug}は実際のカテゴリー・スラッグに置き換えてください。

例えば、’News’というカテゴリーがあれば、single-cat-news.phpファイルを作成します。もし’Travel Tips’というカテゴリーがあれば、single-cat-travel-tips.phpというテンプレートを作成します。

Creating Single Post Template for Categories

これで、これらのテンプレートファイルは完全に空になります。手始めに、テーマフォルダーからsingle.phpファイルのコンテンツをコピー&ペーストして、それぞれのテンプレート内に貼り付けてください。その後、これらのテンプレートを編集して希望の変更を加える必要があります。

完了したら、サイトに行って投稿を表示することができます。この投稿がファイルされているカテゴリー用に作成したテンプレートが使用されます。

さて、2つのカテゴリーに分類された投稿があるとしよう:新規:ニュース」と「旅のヒント」です。WordPressは、アルファベット順で最初に表示される「ニュース」のテンプレートを自動的に表示します。

一方、カテゴリーに投稿し、そのカテゴリー用のテンプレートを作成していない場合、WordPressはテーマの初期設定single.phpテンプレートにフォールバックします。

特定の投稿者のためのカスタム個別投稿テンプレートの作成

特定の投稿者によって書かれた投稿を、投稿日:サイト上で異なるように見せたいとします。カテゴリーで紹介したのと同じテクニックを使えば、コードを使ってそれを行うことができる。

まず、テーマのfunctions.phpファイルまたはコードスニペットプラグインにこのコードを追加する必要があります。

/**
* 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';
 
}

次に、FTPまたはcPanelのファイルマネージャを使ってサイトに接続し、/wp-content/themes/your-theme-folder/に移動します。その中にまだ/single/というフォルダーを作成していないのであれば、今すぐ作成してください。

このフォルダーの中で、テンプレート名に著者のユーザー名を使用してテンプレートを作成する必要があります。例えば、single-author-johnsmith.phpです。

このテンプレートは空になるので、テーマのsingle.phpテンプレートのコンテンツをコピー&ペーストして、出発点として使用することができます。

あなたのサイトにアクセスして、特定の投稿者が作成した投稿を表示できるようになりました。あなたが作成したテンプレートが使用されます。

この投稿が、WordPressでカスタマイザー個別投稿テンプレートを作成する方法を学ぶのにお役に立てば幸いです。また、WordPressサイトの訪問者をトラッキングする方法や、サイトを成長させるために必須の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.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

アバター

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.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

70件のコメント返信を残す

  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. allah ditta

    i want to create a post template like wpbeginer is it possible?

    • WPBeginner Support

      If there is part of our design you like you could recreate that on your site.

      管理者

  3. Jasmine

    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?

  4. Iulian

    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?

  5. Thomas

    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

      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.

      管理者

  6. bob

    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

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

      管理者

  7. Jojo

    I cannot find the template option in Beaver Builder.

    • WPBeginner Support

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

      管理者

  8. John

    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

      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.

      管理者

  9. Ali Jahani

    Hi
    wpbeginner is veryyyyyyyyyy good
    thanks for publish best article

    • WPBeginner Support

      Glad you like our content :)

      管理者

  10. Gregory

    This is a awesome tutorial about WP custom post page.
    Thanks about your help.

    • WPBeginner Support

      You’re welcome, glad you found our tutorial helpful :)

      管理者

  11. Haripal Reddy

    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

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

      管理者

  12. Alice

    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?

  13. aziz

    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?

    • WPBeginner Support

      You would need to create the folder as we explain after the code in the article :)

      管理者

  14. Binesh

    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

  15. Mike

    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

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

      管理者

  16. Jojo

    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!

  17. Jagdish

    I’m one of your silent readers, thoroughly love your blog <3

    • WPBeginner Support

      Thank you, glad you’ve been enjoying our content :)

      管理者

  18. Hil

    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

  19. Malgorzata

    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.

  20. Christopher Krohn

    Fantastic tutorial. Thanks!

  21. STEVE

    Hi, Thanks for the tutorial!

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

    Thanks

  22. TRAVIS

    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?

    • Jarrod

      Just put the code for the template you want to create into single.php.

  23. Jae

    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.

    • Mahbub

      @JAY why not u done that on ur own?

  24. peyman

    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

      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.

  25. Mike

    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

      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;
        }
      
  26. Dzungx Corn

    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.

  27. Sarmad Gardezi

    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 :)

  28. Mike

    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?

  29. Mike

    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

      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.

  30. Ashley

    I cannot get this to work for me, the template never shows in the post editor even after clearing my cache.

  31. Olayinka

    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.

  32. oussama

    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?

  33. Linda Holiner

    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.

  34. Taufiq Mahmud

    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

  35. Pierrick

    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

      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
      ?>
      

      管理者

  36. alex

    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?

  37. Mark

    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

      first copy single.php to the /single folder

      then include this code right before the endforeach;

      else

      return SINGLE_PATH . ‘/single.php’;

  38. Garikai Dzoma

    This has been a great help to me.

  39. Lyssie

    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

      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

      管理者

      • Lyssie

        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

          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

        • WPBeginner Support

          Hi Lyssie,

          Your theme uses content-area class to define the content block’s width. You should be able to see its width when using the inspect tool.

  40. Joe Yee

    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

      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.

      管理者

      • Danielle

        When I put the file in my child theme, I see it in the drop down box but it doesn’t actually apply.

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。