How can I add a view counter to BBPress?

This topic was published by and viewed 3912 times since "". The last page revision was "".

Viewing 1 post (of 1 total)
  • Author
    Posts

  • DevynCJohnson
    Keymaster
    • Topics - 437
    • @devyncjohnson

    To add a view counter to BBPress with the number of views shown on the topic page and topic-forums, follow the below instructions.

    To collect, count, and store topic views in the database, place the below code in the theme's functions.php file. The code will create the "views" post_meta database entry, store views, and increment the views.

    // View Counter
    function get_wpbbp_post_view($postID){
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count==''){
            delete_post_meta($postID, $count_key);
            add_post_meta($postID, $count_key, '0');
            return "0";
        }
        return $count;
    }
    function set_wpbbp_post_view($postID) {
        $count_key = 'post_views_count';
        $count = get_post_meta($postID, $count_key, true);
        if($count == ''){
            add_post_meta($postID, $count_key, '1');
        } else {
            $new_count = $count + 1;
            update_post_meta($postID, $count_key, $new_count);
        }
    }
    function add_wpbbp_topic_counter() {
        global $wp_query;
        $bbp = bbpress();
        $active_topic = $bbp->current_topic_id;
        set_wpbbp_post_view($active_topic);
    }
    add_action('bbp_template_after_single_topic', 'add_wpbbp_topic_counter');

    That code alone is enough to collect and store the topic counts. However, to display the view count, some code must be edited in the BBPress template files.

    To do so, copy plugins/bbpress/templates/default/bbpress/loop-single-topic.php and plugins/bbpress/templates/default/bbpress/loop-topics.php to themes/YOUR-THEME/bbpress/ . Next, go to the directory with the newly copied files. Edit the code as needed to display the views.

    DCJTech.info replaced the "voices" column in "loop-single-topic.php" with <li class="bbp-topic-voice-count"><?php echo get_wpbbp_post_view(bbp_get_topic_id());?></li>. In "loop-topics.php", the "voices" column title was replaced with <li class="bbp-topic-voice-count">Views</li>

    NOTE: Remember to modify the CSS style sheets as needed.

Viewing 1 post (of 1 total)