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の投稿ループで子カテゴリーだけを表示する方法:子カテゴリーを表示する

編集メモ: WPBeginner のパートナーリンクから手数料を得ています。手数料は編集者の意見や評価に影響を与えません。編集プロセスについて詳しく知る。

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の投稿ループで子カテゴリーだけを表示する

まず、カテゴリーを表示するためのコードをテーマファイルから見つける必要があります。これには少し時間がかかるかもしれませんが、コードエディターの検索機能を使えばスピードアップできます。

has_categoryや get_the_category_listのようなカテゴリー関連のコードを探してみてください。それらが見つかれば、正しいファイルにいるはずです。

Twenty Twenty-Oneテーマを使用している場合、探すべきファイルは’inc’フォルダー内のtemplate-tagsファイルです。カテゴリーを表示するためのスニペットです:

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
        );
    }
    echo '</div>';
}

適切なテンプレートファイルが見つからない場合は、WordPressテンプレート階層チートシートをご覧ください。

正しいコードが見つかったので、次のスニペットを追加することができる:

// Get the IDs of categories
    $categories = get_the_category();
    $child_cat_ID = array(); // Array to store child category IDs

    foreach( $categories as $category ) {
        // Check if the category has a parent (i.e., it's a child category)
        if ( $category->parent > 0 ) {
            $child_cat_ID[] = $category->term_id; // Store the child category ID
        }
    }

    if ( !empty($child_cat_ID) ) {
        $output = '<span class="cat-links">' . esc_html__( 'Categorized as ', 'twentytwentyone' );
        foreach($child_cat_ID 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; // Echo the entire output

Twenty Twenty-Oneテーマを使用している場合は、上記のコードをこれらの行の間に置き換えて追加してください:

if ( has_category() || has_tag() ) {
    echo '<div class="post-taxonomies">';
// Replace the code in between these lines
}
    echo '</div>';
}

こんな感じだ:

Editing a theme file to display only child categories

完了したら、変更を保存し、ファイルをWebホスティングサーバーにアップロードします。

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

この投稿が、WordPressの投稿に子カテゴリーだけを表示する方法を学ぶのにお役に立てば幸いです。次は、WordPressでオンラインブログでお金を稼ぐ方法のガイド、またはエキスパートが選ぶ使うべき最高のSEOプラグインとツールをご覧ください。

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$編集プロセスをご覧ください。

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.

究極の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.

返信を残す

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