サポート » 使い方全般 » query postsで特定の投稿だけ表示させない

  • query postsを使って投稿ページ(single.php)の記事の下部に、投稿ページと同じカテゴリの記事をリスト表示したいのですが、リストには現在の投稿ページの記事は表示したくありません。
    そこで現在の投稿ページの投稿IDを取得して、それ以外の記事を表示するとしたいのですが、どうすればいいのでしょうか?

    投稿IDがnの時(「p=$post_id」)ではなく、投稿IDがnではない時としたいのですが、方法がわかりません。

    ご教示の程どうぞ宜しくお願い致します。

    ————————-

    $cat = get_the_category();
    $cat = $cat[0];
    $chekid = $cat->cat_ID;
    $post_id = get_the_ID();
    
    query_posts('posts_per_page=10&cat='.$chekid.'&p='.$post_id);
    if(have_posts()):
    	while(have_posts()):
    		the_post();
    		get_template_part('content', 'title');
    	endwhile;
    endif;

    ————————–

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • モデレーター gatespace

    (@gatespace)

    こんばんは。
    特定の投稿IDを含めたくない場合は、 post__not_in パラメーターを使ってください。

    CodexはWordPressの公式ドキュメントですので一度読まれると良いと思います。

    また、single.phpに書かれるのであれば、当該部分はメインではなループとなるので、
    get_postsを使う方がベターでしょう。

    ※コードを投稿する時はその部分を「code」ボタンを押して囲ってください。

    トピック投稿者 chachajirou

    (@chachajirou)

    gatespaceさん、ありがとうございます!
    お礼が遅くなって申し訳ございません。
    以下のような書き方でうまく表示することが出来ました。

    <ul>
    <?php
    $cat = get_the_category();
    $cat = $cat[0];
    $chekid = $cat->cat_ID;
    $post_id = get_the_ID();
    
    global $post;
    $args = array( 'category' => $chekid );
    $myposts = get_posts( $args );
    foreach( $myposts as $post ) :	setup_postdata($post); ?>
    	<?php if ( $post->ID != $post_id ): ?>
    	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    	<? endif; ?>
    <?php endforeach; ?>
    </ul>
2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「query postsで特定の投稿だけ表示させない」には新たに返信することはできません。