ワードプレスの先頭に固定表示機能は便利で特定の記事を固定しておく場合にはとても便利です。この機能って基本的にトップページにしか反映されないのでカテゴリーページにも対応できたらと思い設置してみました。
割とプラグインで対応するようなケースが多いですが今回はcategory.phpに書き込んで完了です。
category.phpに以下のように記載します。
category.php
<!-- 先頭固定表示 -->
<?php if (!is_paged()) : ?>
<?php $sticky = get_option('sticky_posts');
if(!empty($sticky)):
$get_cat = get_the_category();
$cat = $get_cat[0];
$args = [
'posts_per_page' => 1,
'cat' => $cat->cat_ID,
'post__in' => get_option('sticky_posts'),
];
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();?>
<h2><?php the_title(); ?></h2>
<p><?php the_content(); ?></p>
<?php endwhile;?>
<?php endif;?>
<?php wp_reset_postdata(); ?>
<?php endif;?>
<?php endif;?>
<!-- カテゴリー表示 -->
<?php
$get_cat = get_the_category();
$cat = $get_cat[0];
$args = [
'post__not_in' => get_option('sticky_posts'),
'cat' => $cat->cat_ID,
];
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : ?>
<?php the_archive_title( '<h2 class="page-title">', '</h2>' );
the_archive_description( '<div class="archive-description">', '</div>' );?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post();?>
<?php the_title( sprintf( '<h2 class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' ); ?>
<?php the_excerpt(); ?>
<?php endwhile;endif;?>
先頭固定ページは1件のみ取得してカテゴリーの一番上に表示します。
!is_paged()で2ページ以降は先頭固定表示しないようにします。
get_option(‘sticky_posts’)で一番最初の先頭固定表示の投稿を取得します。カテゴリーページなのでget_the_category()で現在のカテゴリーを取得、posts_per_pageで1件取得、post__inで投稿IDで表示を指定します。これで一番上に固定表示されます。
それ以下は通常のカテゴリー表示ですが’post__not_in’ => get_option(‘sticky_posts’)で先頭固定表示を取得しないようにしてあとはループして表示させれば良いですね。
参考になれば幸いです。
∞Tadashi Suyama∞
あまりcgiは使いたくないのですが使わざるを得ない時があります。仕方なく設置するのですがエラーが出ちゃうんです。なんか知らないけど。 ありがちなのがパーミッションとかパスが問題になるんのですけど...
19 Feb 2022
今回はワードプレス専用のアドレス変更方法をご紹介します。ワードプレスのアドレスはwordpress@~という形で送られてきますが変更可能です。 functions.phpに記載するのですがプラグ...
12 Feb 2022
Sassの遷移は多すぎる今日この頃 Ruby Sass→LibSass→DartSass(いまここ) Ruby SassはSassの最初の実装でしたが、2019年3月26日にサポートが終了しま...
22 Jan 2022
明けましておめでとうございます。 本年も何卒よろしくお願いいたします。 年末年始は雪でしたね、そこまで積もっていませんが。 {% include adsensearticle.html...
10 Jan 2022
最近はjQueryよりvueで書いた方が楽ではないかと思い学習中です。 そもそもVuejsはドキュメントが日本語対応なので試しやすいし情報も豊富なので学習しやすいです。 3大フレームワークと呼...
02 May 2021
ウェブエンジニアの須山のブログです。
WEBに関することや個人的に関心のあることについて書きます。主に技術系ブログです。