LoginSignup
39

More than 5 years have passed since last update.

WordPressで投稿のアーカイブ(投稿一覧)を設定する

Last updated at Posted at 2016-10-12

WordPressは
トップページと投稿のアーカイブのテンプレートが基本的に同じ。

管理画面の表示設定フロントページの表示
固定ページにすればすんなり分けられるけど
固定ページつくるのは気持ち悪い。

ので探していたら

v4.4から追加されたregister_post_type_argsに引っ掛ければで設定を変えられるらしいことがわかる。
投稿アーカイブを有効にする (WordPress 4.4以降)

っていうことでやったらできたにはできたけど
シングルのスラッグとアーカイブのスラッグが同じだと問題が。

投稿のパーマリンクを
/news/%post_id%
としている場合で
$args['has_archive'] = 'news';

とすると
/news/ でアーカイブは表示できるが
/news/1 とかでシングルが404になる。

ので却下で海外を探してみるとあった。
Creating a blog post archive at /blog/ without awkwardly publishing a page
フィードも考慮されていてマーベラス。

自分用に変えると

functions.php
/**
 * 投稿のアーカイブページを設定
 */
add_filter('register_post_type_args', function($args, $post_type) {
    if ('post' == $post_type) {
        global $wp_rewrite;
        $archive_slug = 'news';
        $args['label'] = 'ニュース';
        $args['has_archive'] = $archive_slug;
        $archive_slug = $wp_rewrite->root.$archive_slug;
        $feeds = '(' . trim( implode('|', $wp_rewrite->feeds) ) . ')';
        add_rewrite_rule("{$archive_slug}/?$", "index.php?post_type={$post_type}", 'top');
        add_rewrite_rule("{$archive_slug}/feed/{$feeds}/?$", "index.php?post_type={$post_type}".'&feed=$matches[1]', 'top');
        add_rewrite_rule("{$archive_slug}/{$feeds}/?$", "index.php?post_type={$post_type}".'&feed=$matches[1]', 'top');
        add_rewrite_rule("{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type={$post_type}".'&paged=$matches[1]', 'top');
    }
    return $args;
}, 10, 2);

で無事にarchive.phpで読めるようになったと。

ちなみに

$args['label'] = 'ニュース';
てやると
get_post_type_object($post_type)->label;
を使っても「投稿」と表示されずに「ニュース」と表示できる。

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
39