Count identical post titles

时间:2018-03-14 作者:Rookie

我在WP网站上有一个评论部分。

我想在“评论”类别中统计具有相同标题的帖子,并显示计数器。

我用tag字段成功地做到了这一点:

                <?php
                global $post;
                $postslist = get_posts( array( \'post_type\' => \'reviews\', \'posts_per_page\' => 20, \'order\'=> \'ASC\', \'orderby\' => \'date\' ) );
                foreach ( $postslist as $post ){
                    setup_postdata($post);
                    ?>

                            <?php

                                // Tag counter 
                                $post_tags = get_the_tags($post->ID);
                                if ($post_tags) {       
                                    foreach($post_tags as $tag){
                                        echo \'<span class="review-count">\' . $tag->count . \' review(s)\'  . \'</span>\';
                                }
                            }
                            ?>
但认为使用标题字段更方便

1 个回复
SO网友:WebElaine

我假设您的原始代码末尾有一个结尾},如下所示:

<?php
    global $post;
    $postslist = get_posts( array( \'post_type\' => \'reviews\', \'posts_per_page\' => 20, \'order\'=> \'ASC\', \'orderby\' => \'date\' ) );
    foreach ( $postslist as $post ){
        setup_postdata($post);

        // Tag counter 
        $post_tags = get_the_tags($post->ID);
        if ($post_tags) {       
            foreach($post_tags as $tag){
                echo \'<span class="review-count">\' . $tag->count . \' review(s)\'  . \'</span>\';
            }
        }
    }
?>
您需要设置一个数组来保存您的foreach 循环,使其持续。

<?php
    global $post;
    $postslist = get_posts( array( \'post_type\' => \'reviews\', \'posts_per_page\' => 20, \'order\'=> \'ASC\', \'orderby\' => \'date\' ) );
    // Set up an empty array
    $review_titles = array();
    foreach ( $postslist as $post ) {
        setup_postdata($post);

        // Use the title rather than tags
        $review_title = $post->post_title;
        // See if this title already exists in the array
        foreach($review_titles as $key => $val) {
            // If the title matches, add to its count
            if($val[\'title\'] == $review_title) {
                $count = $val[\'count\'] + 1;
                $review_titles[$key][\'count\'] = $count;
                // Stop looping since we already found a match
                break;
            }
            // The title doesn\'t match, so add it to the array with count 1
            else {
                $review_titles[] = array(\'title\' => "$review_title", \'count\' => 1);
            }
        }
    }
?>

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post