表示記事と同階層カテゴリの一つ前の記事を取得したい
もしかしたらお望みのものと違うかもしれません。
同じパターンでカテゴリーにチェックがあるものを探してきます。
カテゴリーを純粋な分類以外にも使っている場合(お勧め記事など)は、意図した通りにはならないでしょう。
「指定記事より前」という指定ができない
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>';
}