サポート » 使い方全般 » この投稿を先頭に固定表示のカスタマイズ

  • 解決済 shinichi_ntrue

    (@shinichi_ntrue)


    この投稿を先頭に固定表示を3件設定しています。
    パソコンページは3件で問題ないのですが
    モバイルページでは1件で表示したいと考えています。
    テーマはパソコンとモバイルで分けて作っています。

    調べたところignore_sticky_postsの数字が
    件数に該当するとのことだったので
    1に変更しましたが3件表示のままでした。

    管理画面の記事で先頭に固定表示を3件設定しまうと
    そちらが優先されるのでしょうか。

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

    ignore_sticky_posts は先頭固定表示の投稿を無視するかどうかを指定する真偽値です。件数を指定するものではありません。
    先頭固定表示の件数を指定する場合は、メインのループとは切り離したほうがいいかなとおもいます。

    例)

    // 先頭固定表示用のループ
    $limit_count = wp_is_mobile() ? 1 : 3; // 件数を指定
    $sticky = get_option( 'sticky_posts' );
    $the_query = new WP_Query( array(
    	'posts_per_page' => $limit_count,
    	'post__in' => $sticky,
    	'ignore_sticky_posts' => 1
    ) );
    while ( $the_query->have_posts() ) {
    	$the_query->the_post();
    	?>
    	<p><?php the_title(); ?></p>
    	<?php
    }
    wp_reset_postdata();
    
    // メインのループ
    :
    • この返信は7年、 2ヶ月前にishitakaが編集しました。理由: 誤記
    トピック投稿者 shinichi_ntrue

    (@shinichi_ntrue)

    ありがとうございます。
    さっそく試してみます。

    トピック投稿者 shinichi_ntrue

    (@shinichi_ntrue)

    あれから試してみたのですがうまくいきませんでした。
    下記の場合ですとどのようにすればいいでしょうか。

    $sticky = implode(“,”,get_option(‘sticky_posts’));
    if($sticky):
    $posts = get_posts(‘include=’.$sticky);
    foreach($posts as $post):

    if ($post){

    LABE

    (@latobeam)

    そのコードでは、固定表示記事がすべて表示されてしまうと思います。
    1件に限定する場合は get_option('sticky_posts') の時点で1件だけを取り出すことができます。

    $sticky = reset(get_option('sticky_posts'));
    $my_posts = get_posts('include='.$sticky);

    ただ、この方法では「どの1件を表示するか」を選べないので、これを選べるようにするには include の代わりに posts_per_pagepost__in を使い、さらに orderby なんかで条件を指定することになります。
    orderby のデフォルトは日時順(新しい順)なので、何も指定しなければ最新の固定表示記事が表示されます。

    $sticky = get_option('sticky_posts');
    $my_posts = get_posts(array(
        'posts_per_page' => 1,
        'post__in' => $sticky,
    ));
    トピック投稿者 shinichi_ntrue

    (@shinichi_ntrue)

    ありがとうございます。
    試してみます。

5件の返信を表示中 - 1 - 5件目 (全5件中)
  • トピック「この投稿を先頭に固定表示のカスタマイズ」には新たに返信することはできません。