• お世話になっております。

    実現したいことは…
    記事(post)のsingle表示ページについて
    表示記事と同階層カテゴリの一つ前の記事を取得したいと考えています。
    いわゆる「〇〇カテゴリの前の記事」といった感じです。

    `get_adjacent_post(true)

    でドンピシャじゃん、って思ったのですが、
    コレで帰ってくる投稿には、親階層のカテゴリにある記事も含まれるようです。

    はてさて、query_postsを使うのかな?
    っと思いましたが、「指定記事より前」という指定ができないような気がします。
    日付指定はできますが、同じ日に投稿された、より新しい記事も含まれてしまいそうです。

    なにとぞよろしくお願いいたします。

1件の返信を表示中 - 1 - 1件目 (全1件中)
  • pluto1234

    (@pluto1234)

    表示記事と同階層カテゴリの一つ前の記事を取得したい

    もしかしたらお望みのものと違うかもしれません。
    同じパターンでカテゴリーにチェックがあるものを探してきます。
    カテゴリーを純粋な分類以外にも使っている場合(お勧め記事など)は、意図した通りにはならないでしょう。

    「指定記事より前」という指定ができない

    query_posts() やget_posts() の指定だけではできません。

    ★ functions.php

    function general_previous_post($terms)
    {
        $args = array(
            'post_type'        => 'post',
            'category__and'    => $terms,
            'order'            => 'ASC',
            'numberposts'      => 1,
            'suppress_filters' => false
        );
        add_filter( 'posts_where', 'my_previous_post_where',10,1);
        $previous_post = get_posts($args);
        remove_filter( 'posts_where', 'my_previous_post_where' );
        if(!empty($previous_post)) {
            return $previous_post[0];
        } else {
            return false;
        }
    }
    
    function my_previous_post_where( $where = '' ) {
        global $post;
        $where .= " AND post_date > '" . $post->post_date . "'";
        return $where;
    }

    ★ single.pjhp

    $taxonomy = 'category';
    $terms = get_the_terms($post->ID,$taxonomy);
    $term_array = array();
    foreach($terms as $term) $term_array[] = $term->term_id;
    
    $p_post = general_previous_post($term_array);
    if ($p_post) {
        echo '<p>前の記事:'.esc_html($p_post->post_title).'</p>';
    }

1件の返信を表示中 - 1 - 1件目 (全1件中)
  • トピック「記事ページに「同階層カテゴリの前の記事」リンクを表示したい」には新たに返信することはできません。