サポート » 使い方全般 » カテゴリーページに先頭固定を使用したい

  • 解決済 wanwanco

    (@wanwanco)


    現在、カテゴリーページを表示しているページに先頭固定をしたいと思い悪戦苦闘しています。
    今現在は以下のような感じで入れています。

    			<!-- 先頭固定表示 -->
    			<?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();?>
    						<div class="post-headline">
    						
    										<div class="post-date"><?php the_time('Y') ?>.<?php the_time('m') ?>.<?php the_time('d') ?></div>
    										<div class="post-text">
    											<div class="post-title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>
    										</div>
    						
    						</div>
    						<?php endwhile;?>
    					<?php endif;?>
    					<?php wp_reset_postdata(); ?>
    				<?php endif;?>
    			<?php endif;?>
    
    			<!-- 通常のカテゴリー表示 -->
    			<?php if (have_posts()) : ?>
    			<?php while (have_posts()) : the_post(); ?>
    			<div class="post-headline">
    
    				<div class="post-date"><?php the_time('Y') ?>.<?php the_time('m') ?>.<?php the_time('d') ?></div>
    				<div class="post-text">
    					<div class="post-title"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>
    				</div>
    
    			</div>
    			<?php endwhile; ?>
    
    			<div id="post-index">
    				<p id="page-befor"><?php previous_posts_link(); ?></p>
    				<p id="page-next"><?php next_posts_link(); ?></p>
    				<?php else : ?>
    				<?php endif; ?>
    			</div>
    

    この方法ですと、一応は先頭に固定は出来るのですが、固定リンクが下のカテゴリーにも見えてしまい、見苦しい状態です。
    出来れば固定したリンクは店頭にのみにして、表示したいのですが、どうやってやればいいか分かりません。
    もし分かる方がいらっしゃいましたら、教えて頂けると助かります。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • こんにちは

    pre_get_posts フックを利用すると良いかと思います。
    https://wpdocs.osdn.jp/プラグイン_API/アクションフック一覧/pre_get_posts

    カテゴリーページより先頭固定を除外する例:

    function pre_get_posts_exclude_sticky_category( $query ) {
    	if ( ! is_admin() && $query->is_main_query() ) {
    		if ( $query->is_category ) {
    			$sticky_posts = get_option( 'sticky_posts' );
    			if ( ! empty( $sticky_posts ) ) {
    				$query->set( 'post__not_in', $sticky_posts );
    			}
    		}
    	}
    }
    add_action( 'pre_get_posts', 'pre_get_posts_exclude_sticky_category' );
    トピック投稿者 wanwanco

    (@wanwanco)

    有り難う御座います。
    試してみます。

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「カテゴリーページに先頭固定を使用したい」には新たに返信することはできません。