LoginSignup
0
1

More than 5 years have passed since last update.

Wordpressで常に特定カテゴリの最新記事にアクセスできるリンクを作成する

Posted at

要件

例えば、以下のような要件。
・バナー等固定でリンクを貼り付ける箇所に最新記事へのリンクを貼りたい。
・投稿記事に「最新記事はこちら」といったテキストリンクをコピペで貼り付けておき、過去記事を編集せずに常に特定カテゴリの最新記事にアクセスできるようにしたい。

コード

functions.php内に書いていきます。

functions.php
function custom_category_redirect($request)
{
    if (isset($_GET['latest'])
        && isset($request->query_vars['category_name'])) {

        $latest = new WP_Query(array(
            'category_name' => $request->query_vars['category_name'],
            'posts_per_page' => 1,
        ));
        if ($latest->have_posts()) {
            wp_redirect(get_permalink($latest->post->ID));
            exit;
        }

    }
}
add_action('parse_request', 'custom_category_redirect');

これでhttp://example.com/category/some-category/?latestのような形式でリンクを貼ると各カテゴリの最新記事にリダイレクトします。

パーマリンクの設定からカテゴリーベースを変更している場合、/category/の部分を任意で設定したものに変えます。
アクションフックのparse_requestはリクエスト処理に対して何らかの操作を加える際に用います。

参考

0
1
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
1