0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WordPress反省】カスタム投稿のカテゴリー設定ミス

Posted at

症状

カスタム投稿news専用のカテゴリーアーカイブに、取得したカテゴリー名からリンクさせたかった。テスト投稿をいくつか入れたが投稿なしになっていた。
「お知らせ」でarchive-news.phpのサイドバーにカテゴリー名と月名からそれぞれの一覧に飛ばしたかった。
月別は問題なく一覧表示されたが、カテゴリーはリンク先が/category/example/となり、投稿が空だった。

原因

カテゴリー名取得にget_terms()関数を使い、`'post_type' => 'news',の指定でいけるだろうと思っていた。

archive-news.php
$categories = get_terms(array(
 'taxonomy' => 'category',
 'post_type' => 'news',
//  以下略
 ));

そして

archive-news.php
// カテゴリー名とリンクを出力
if (!empty($categories) && !is_wp_error($categories)) {
    echo '<ul>';
    foreach ($categories as $category) {
        // カテゴリーリンクを取得
        $category_link = get_term_link($category);

        // リンクが正しく取得できたかを確認
        if (!is_wp_error($category_link)) {
            echo '<li><a href="' . esc_url($category_link) . '">' . esc_html($category->name) . '</a></li>';
        }
    }
    echo '</ul>';
}
?>

解決策

1: カスタムタクソノミーでカテゴリーを作り直して/category-news/example/で表示させた。
taxonomy-news-category.phpを設置してfunctions.phpに以下を記述

functions.php
function create_news_taxonomy() {
 register_taxonomy(
 'news-category', // カスタムタクソノミー名
 'news', // カスタム投稿タイプ名
 array(
 'label' => __('News Categories'),
 'rewrite' => array('slug' => 'news-category'),
 'hierarchical' => true,
 )
 );
}
add_action('init', 'create_news_taxonomy')

2: 使わなかったが、/category/example/で表示できるように。

functions.php
function create_custom_post_type() {
 register_post_type('news',
 array(
 'labels' => array(
 'name' => __('News'),
 'singular_name' => __('News')
 ),
 'public' => true,
 'has_archive' => true,
 'rewrite' => array('slug' => 'news'),
 'supports' => array('title', 'editor', 'thumbnail'),
 'taxonomies' => array('category') // ここでデフォルトのカテゴリーを使えるようにする
 )
 );
}
add_action('init', 'create_custom_post_type');

なお月別は<?php wp_get_archives(); ?>だけで済む。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?