
はじめに
WordPressのカスタム投稿には「ページの先頭に固定表示する」機能が備わっておりません。
そこで、 Seamless Sticky Custom Post Types
というプラグインを活用して、カスタム投稿の任意の記事をページの先頭に固定表示する機能を実装していこうと思います。
Seamless Sticky Custom Post Typesの役割
公式の説明を要約すると
- カスタム投稿の記事に先頭固定表示ボタンを設置する
-
先頭固定表示ボタンにチェックを入れた記事IDは
get_option('sticky_posts')
から取得可能 - なるべくシームレスにするためクエリは変更しない
つまり、このプラグインの役割は
設置したボタンにチェックが入っている記事IDをDBに格納する
です。
DBに格納した記事IDの配列は get_option('sticky_posts')
で取得できます。
Seamless Sticky Custom Post Typesを利用して記事を取得する
以下の条件における記事を1つのループにまとめて表示します。
カスタム投稿タイプ | post_type_slug |
記事取得数(1ページあたり) | 10 |
表示順 | 先頭固定表示にチェックが入っている記事、それ以外の記事の順で、それぞれ公開日時が新しい順で取得 |
返り値 |
$display_results |
$sticky_args = [
 'posts_per_page' => -1,
 'order' => 'DESC',
 'post_status' => 'publish',
 'post_type' => 'post_type_slug',
 'post__in' => get_option('sticky_posts')
];

$args = [
 'posts_per_page' => -1,
 'order' => 'DESC',
 'post_status' => 'publish',
 'post_type' => 'post_type_slug',
 'post__not_in' => get_option('sticky_posts')
];

$sticky_query = new WP_Query($sticky_args); // 固定表示の記事を取得
$the_query = new WP_Query($args); // 固定表示以外の記事を取得

$results = array_merge($sticky_query->posts, $the_query->posts);
$display_results = array_slice($results, (max(1, get_query_var('paged')) - 1) * 10, 10); // 1ページに10記事ごと取得する
$display_results
は array
型で返ってくるのでご注意ください。
補足
先頭固定表示ボタンにチェックを入れた記事IDは wp_options
テーブルに格納されております。
mysql> SELECT option_value FROM wp_options WHERE option_name = 'sticky_posts';
+----------------------------+
| option_value |
+----------------------------+
| a:2:{i:0;i:127;i:1;i:103;} |
+----------------------------+
さいごに
記事を表示するループを1つにまとめることで、特にページネーションが存在するページにおいて起こりうる問題を解消することができます。
数ある手法の中の1つとしてご参考にしてください。