サポート » 使い方全般 » 記事ページ(single.php)で、次の記事(前の記事)のコメント数を取得(表

  • 解決済 umineko

    (@umineko)


    いつもお世話になっております。m(_ _)m

    WordPressフォーラムの過去のトピックや、
    Googleで「次の記事 コメント数 WordPress」などで検索してみましたが、解決法が見つかりませんでしたため、質問いたします。

    現在の記事ページのコメント数は
    <?php comments_number(); ?>
    で取得することができたのですが、現在の記事ページの次の記事(前の記事)のコメント数を取得するには、どのような方法で実現できるのでしょうか?

    アドバイスを頂けたら幸いです。m(_ _)m

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • ポストの順序は、pevious_post_link(), next_post_link() と同じです。

    ★functions.php

    function previous_comments_num()
    {
    	$args = array(
    		'post_type'        => 'post',
    		'orderby'          => 'post_date',
    		'order'            => 'ASC',
    		'numberposts'      => 1,
    		'suppress_filters' => false
    	);
    	add_filter( 'posts_where', 'previous_comments_num_where');
    	$previous_post = get_posts($args);
    	remove_filter( 'posts_where', 'previous_comments_num_where' );
    	if(!empty($previous_post)) {
    		$num = get_comments_number($previous_post[0]->ID);
    	} else {
    		$num = -1;
    	}
    	return $num;
    }
    
    function next_comments_num()
    {
    	$args = array(
    		'post_type'        => 'post',
    		'orderby'          => 'post_date',
    		'order'            => 'DESC',
    		'numberposts'      => 1,
    		'suppress_filters' => false
    	);
    	add_filter( 'posts_where', 'next_comments_num_where');
    	$next_post = get_posts($args);
    	remove_filter( 'posts_where', 'next_comments_num_where' );
    	if(!empty($next_post)) {
    		$num = get_comments_number($next_post[0]->ID);
    	} else {
    		$num = -1;
    	}
    	return $num;
    }
    
    function previous_comments_num_where( $where = '' ) {
        global $post;
        $where .= " AND post_date > '" . $post->post_date . "'";
        return $where;
    }
    
    function next_comments_num_where( $where = '' ) {
        global $post;
        $where .= " AND post_date < '" . $post->post_date . "'";
        return $where;
    }

    ★single.php

    <?php
    $prev_num = previous_comments_num();
    if ($prev_num != -1) echo "$prev_num<br />";
    $next_num = next_comments_num();
    if ($next_num != -1) echo $next_num;
    ?>

    トピック投稿者 umineko

    (@umineko)

    pluto1234様

    たびたびお世話になります。m(_ _)m

    お教えいただいたコードで見事、実現できました!

    いつもご親切にして頂き、本当に感謝しております。
    ありがたく、コードを利用させていただきます。

    ご回答、ありがとうございました。m(_ _)m

2件の返信を表示中 - 1 - 2件目 (全2件中)
  • トピック「記事ページ(single.php)で、次の記事(前の記事)のコメント数を取得(表」には新たに返信することはできません。