Produced by FOURIER

任意のカスタム投稿記事を先頭固定表示する

TakahashiTakahashi calender 2024.2.15

はじめに

WordPress のカスタム投稿には「ページの先頭に固定表示する」機能が備わっておりません。

そこで、Seamless Sticky Custom Post Types というプラグインを活用して、カスタム投稿の任意の記事をページの先頭に固定表示する機能を実装していこうと思います。

Seamless Sticky Custom Post Types

Seamless Sticky Custom Post Types

Extends the native sticky post functionality to custom post types in a way that is identical to default posts.

https://ja.wordpress.org/plugins/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_resultsarray 型で返ってくるのでご注意ください。

補足

先頭固定表示ボタンにチェックを入れた記事 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 つとしてご参考にしてください。

新しいメンバーを募集しています

Takahashi

Takahashi / Engineer

主にWordPressを担当しています。 趣味はフットサル、サッカー観戦。