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の投稿に多くのカテゴリーを追加すると、物事が少し混雑して見えるようになることがあります。複数のカテゴリー、特に親カテゴリーと子カテゴリーがあると、レイアウトが乱雑になり、読者が探しているものを見つけにくくなります。

投稿ごとに子カテゴリーだけを表示したほうがすっきりするのでは?

このガイドでは、WordPressのテーマファイルを調整して投稿ループに子カテゴリーのみを表示し、ブログをより合理的でユーザーフレンドリーな感じにする方法を紹介します。

Showing only child categories inside WordPress post loop

なぜWordPressの投稿ループで子カテゴリーだけを表示するのか?

WordPressでブログを作成する場合、カテゴリーやタグを使ってコンテンツを整理することができます。

読者が興味深いコンテンツをより早く見つけられるように、子カテゴリー(またはサブカテゴリー)を作ることもできる。

例えば、あなたが旅行ブログを持っているなら、「目的地」カテゴリーを作成し、「ヨーロッパ」、「アメリカ」、「オーストラリア」などの子カテゴリーを持つかもしれない。

デフォルト設定では、ほとんどのWordPressテーマは投稿の親カテゴリと子カテゴリをすべて表示します。

Displaying the child categories only in the WordPress post loop

しかし、カテゴリーをたくさん使うと、ブログのページがごちゃごちゃして複雑に見えてしまうかもしれません。また、読者が興味のあるカテゴリーを見つけるのも難しくなります。

そのため、投稿の一般的な親カテゴリを非表示にして、子カテゴリだけを表示したい場合があります。ということで、WordPressの投稿ループで子カテゴリーだけを表示する方法を見てみましょう。

WordPressテーマファイルを編集する前に:覚えておくべきポイント

このガイドは、WordPressテーマファイルのコーディングや編集に慣れている方を対象としています。チュートリアルの前にやっておくべきことがあります:

  1. まず、サイトにFTP接続するか、ホスティングサービスのファイルマネージャーを開いて、ファイルにアクセスする必要があります。
  2. 初心者の方は、スニペットをWordPressに貼り付ける方法の初心者ガイドをご覧ください。
  3. この方法に従うには、バックアップを作成するか、ステージングサイトを使用することをお勧めします。この方法であれば、何か問題が発生しても、本番サイトが影響を受けることはありません。

最後に、このガイドはクラシックWordPressテーマにのみ適用されます。ブロックテーマはテーマファイルの構造が異なります。

WordPressの投稿ループで子カテゴリーだけを表示する

このチュートリアルでは、Bluehostファイルマネージャを使用してテーマファイルを編集する方法を説明します。しかし、ホスティングサービスに関係なく、手順は似ているはずです。

まず、Bluehostのダッシュボードにログインし、 ‘ウェブサイト’タブに移動します。次に、編集したいサイトの「設定」をクリックします。

Bluehost site settings

次に、クイックリンクのセクションまでスクロールダウンします。

次に、「ファイルマネージャー」ボタンをクリックします。

Accessing a website's file manager in Bluehost

ファイルマネージャーが開きます。

次に、テーマファイルの中からカテゴリーを表示するためのコードを見つける必要があります。サイトのpublic_htmlフォルダー wp-content ” themes あなたの現在のテーマのフォルダーに行くことでこれを始めることができます

この段階では、編集する正しいファイルを見つけるために、各ファイルやフォルダーを一つずつ開く必要があるかもしれません。ひとつは、has_categoryや get_the_category_listのようなカテゴリー関連のコードを探してみることです。それらが見つかれば、正しいファイルにいるはずです。

適切なテンプレートファイルが見つからない場合は、WordPressテンプレート階層チートシートと編集するテーマファイルの見つけ方ガイドをご覧ください。

Twenty Twenty-Oneテーマを使用している場合、探すべきファイルは’inc’フォルダー内のtemplate-tagsファイルです。見つけたら、そのファイルを右クリックして「編集」を選択します。

Opening the inc folder for the Twenty Twenty One theme in Bluehost file manager

このファイルでは、カテゴリーとタグの表示を担当するスニペットである:

if ( has_category() || has_tag() ) {

				echo '<div class="post-taxonomies">';

				$categories_list = get_the_category_list( wp_get_list_item_separator() );
				if ( $categories_list ) {
					printf(
						/* translators: %s: List of categories. */
						'<span class="cat-links">' . esc_html__( 'Categorized as %s', 'twentytwentyone' ) . ' </span>',
						$categories_list // phpcs:ignore WordPress.Security.EscapeOutput
					);
				}

				$tags_list = get_the_tag_list( '', wp_get_list_item_separator() );
				if ( $tags_list && ! is_wp_error( $tags_list ) ) {
					printf(
						/* translators: %s: List of tags. */
						'<span class="tags-links">' . esc_html__( 'Tagged %s', 'twentytwentyone' ) . '</span>',
						$tags_list // phpcs:ignore WordPress.Security.EscapeOutput
					);
				}
				echo '</div>';
			}
		} else {

正しいコードを見つけたので、そのスニペット全体を次のように置き換えることができる:

if ( has_category() || has_tag() ) {

    echo '<div class="post-taxonomies">';

    // Get the list of categories
    $categories = get_the_category();
    $child_cat_IDs = array(); // Array to store child category IDs
    $parent_cat_IDs = array(); // Array to store parent category IDs
 
    foreach ( $categories as $category ) {
        if ( $category->parent > 0 ) {
            $child_cat_IDs[] = $category->term_id; // Store the child category ID
        } else {
            $parent_cat_IDs[] = $category->term_id; // Store the parent category ID
        }
    }

    // Output child categories if there are any
    if ( !empty($child_cat_IDs) ) {
        $output = '<span class="cat-links">' . esc_html__( 'Categorized as ', 'twentytwentyone' ) . ' ';
        foreach ( $child_cat_IDs as $cat_id ) {
            $cat_link = get_category_link($cat_id);
            $cat_name = get_cat_name($cat_id);
            $output .= '<a href="' . esc_url($cat_link) . '">' . esc_html($cat_name) . '</a> ';
        }
        $output .= '</span>'; // Close the span tag after the loop
        echo $output; // Output the child category links

    // Output parent categories if there are no child categories
    } elseif ( !empty($parent_cat_IDs) ) {
        $output = '<span class="cat-links">' . esc_html__( 'Categorized as ', 'twentytwentyone' ) . ' ';
        foreach ( $parent_cat_IDs as $cat_id ) {
            $cat_link = get_category_link($cat_id);
            $cat_name = get_cat_name($cat_id);
            $output .= '<a href="' . esc_url($cat_link) . '">' . esc_html($cat_name) . '</a> ';
        }
        $output .= '</span>'; // Close the span tag after the loop
        echo $output; // Output the parent category links
    }

    // Handle tags
    $tags_list = get_the_tag_list('', wp_get_list_item_separator());
    if ( $tags_list && ! is_wp_error( $tags_list ) ) {
        printf(
            /* translators: %s: List of tags. */
            '<span class="tags-links">' . esc_html__( 'Tagged %s', 'twentytwentyone' ) . '</span>',
            $tags_list // phpcs:ignore WordPress.Security.EscapeOutput
        );
    }

    echo '</div>'; // Close post-taxonomies div
}
} else {

このコード・スニペットは、まず投稿に割り当てられているすべてのカテゴリーを特定します。そして、それぞれのカテゴリーに親がいるかどうかをチェックします。

もしそうであれば、それは子カテゴリーということになり、表示リストに追加されます。親カテゴリーはスキップされ、投稿のカテゴリー分けがよりすっきりと具体的に表示されます。

コードを置き換えると、こんな感じになります:

Making changes to the code that displays the category list in the post loop using the Bluehost file manager

完了したら、変更を保存してください。

ここで、1つ以上の子カテゴリーを持つ投稿にアクセスする必要があります。親カテゴリーが非表示になり、WordPressが子カテゴリーのみを表示しているのがわかるだろう。

Result of editing the code to display only the child category in the post loop

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

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

  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. Mike says

    Managed it!

    foreach((get_the_category()) as $childcat) {
    $parentcat = $childcat->category_parent;
    if (cat_is_ancestor_of(10, $childcat)) {
    echo get_cat_name($parentcat);
    }
    }

  3. MIke says

    I have three main categories and this code is successfully working in my single page loop to echo the actual selected category name.
    I now want to echo the parent of the category. The complication is that I have two layers below the main category (3 levels) and I want to echo the one level parent not the top level parent. It seems easy to echo the top parent, but I haven’t seem any code to return the child level category of a grandchild category?

  4. Marian Rick says

    This is a great piece of code. Thanks a lot so far!

    For one of my projects I have to go further, and display only the lowest subcategory. So there may be three levels, (Forms -> Squares -> Big Squares). With this code all subs (Squares -> Big Squares) are displayed. How can I tell this code to repeat the process till only the last child is found and displayed?

    If you’ve got any solutions for that you are my heroes once again! Keep up your great work and blog!

    • Editorial Staff says

      If you are trying to display a list of all child categories, then use wp_list_categories() function. It has parameters that allow you to list only child categories or only parent categories. But that doesn’t work for the case that we are talking about in this article.

      管理者

  5. Keith Davis says

    Great snippets of info from you guys.
    I really have to start to get into this PHP.

    Great site boys and I notice that you are up to Pagerank 6!
    How about a couple of posts on upping your pagerank.

返信を残す

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