wordpress WordPress投稿画面に次・前の投稿のナビゲーションを付ける 作成日: 2026年1月20日
これも開発案件での実装試験中に投稿を初期化したりする必要の中で、一覧に戻って探すのが面倒なので作った。
Gutenbergが嫌いなので旧エディタでのみ確認。Gutenbergでも動くかも。
- function.phpに追記すればOK
- テーマやPL次第でエラーになる可能性あり
- 稼働確認=作った環境はWP6.8 PHP8x
//投稿画面でのmenu_order順またはデフォルト公開順に次・前の投稿へのリンクを作るadd_action('init', 'my_add_post_attributes');function my_add_post_attributes() { add_post_type_support('post', 'page-attributes');}add_action('add_meta_boxes', 'add_post_nav_metabox');function add_post_nav_metabox() { add_meta_box('post_nav_box', '投稿ナビゲーション', 'render_post_nav_metabox', 'post', 'side', 'high');}function render_post_nav_metabox($post) {$all_posts = get_posts(array('post_type' => $post->post_type,'post_status' => array('publish', 'future', 'draft', 'pending', 'private'),'posts_per_page' => -1,'orderby' => array('menu_order' => 'ASC', 'ID' => 'ASC'),)); $current_index = -1; foreach ($all_posts as $index => $p) { if ($p->ID == $post->ID) { $current_index = $index; break; } } echo '<div style="padding: 5px 0;">'; if ($current_index !== -1) {$next_post = isset($all_posts[$current_index + 1]) ? $all_posts[$current_index + 1] : null;$prev_post = isset($all_posts[$current_index - 1]) ? $all_posts[$current_index - 1] : null; // 【次へ】 新しい方へ(ID増) if ($next_post) { $next_url = get_edit_post_link($next_post->ID); echo '<p><a href="' . $next_url . '" class="button button-primary" style="display:block; text-align:center;">次へ:新しい投稿 (ID:' . $next_post->ID . ')</a></p>'; } // 【前へ】 古い方へ(ID減) if ($prev_post) { $prev_url = get_edit_post_link($prev_post->ID); echo '<p style="margin-top:10px;"><a href="' . $prev_url . '" class="button" style="display:block; text-align:center;">前へ:古い投稿 (ID:' . $prev_post->ID . ')</a></p>'; } } echo '</div>'; echo '<p class="description" style="margin-top:10px; border-top:1px solid #ddd; padding-top:10px;">現在のID: ' . $post->ID . ' / 順序: ' . $post->menu_order . '</p>';}
デフォルトの公開日順対応。
当方制作の投稿順並び替えコード連動。
WPデフォルトのソート順以外の並び替えの場合
$next_post = isset($all_posts[$current_index + 1]) ? $all_posts[$current_index + 1] : null;
$prev_post = isset($all_posts[$current_index – 1]) ? $all_posts[$current_index – 1] : null;
この2行のnext_post、prv_postを逆にした方がソート順に整合する場合あり。