Want to add upvotes and downvotes to bbPress topics and replies? I’ll show you the core pieces I use when building a voting system from scratch: rendering controls, sending a vote, recording it, and sorting the results. You can follow the code to build your own version, then decide whether maintaining it is worth the effort.
This is a small logged-in-user example, not a drop-in production plugin. Put the PHP in a small custom plugin and the JavaScript and CSS in files alongside it. Use your own prefix if you adapt the code. Test on a staging site first; a public forum also needs a deliberate guest-voting policy, abuse controls, and a plan for simultaneous votes.
Create wpftw-vote-example/wpftw-vote-example.php under wp-content/plugins with the header below, then append the PHP blocks from this guide to that file. Save the JavaScript as wpftw-vote.js and the CSS as wpftw-vote.css in the same folder. Activate the example plugin only on your test site.
<?php
/**
* Plugin Name: WPFTW bbPress Vote Example
* Description: Minimal logged-in-user voting tutorial for bbPress.
* Version: 0.1.0
*/
if ( ! defined( 'ABSPATH' ) ) { exit; }
1. Render voting controls for topics and replies
bbPress exposes template hooks where a theme can display controls. Here I use the topic-title hook for topics and the reply-content hook for replies. The post ID comes from bbPress, not from a guessed global post. Each button carries its direction, and the displayed score comes from saved counts.
add_action( 'bbp_theme_before_topic_title', 'wpftw_render_vote_buttons' );
add_action( 'bbp_theme_before_reply_content', 'wpftw_render_vote_buttons' );
function wpftw_render_vote_buttons() {
if ( ! function_exists( 'bbp_get_topic_id' ) || ! is_user_logged_in() ) {
return;
}
$post_id = current_action() === 'bbp_theme_before_reply_content'
? (int) bbp_get_reply_id()
: (int) bbp_get_topic_id();
if ( ! $post_id ) {
return;
}
$ups = max( 0, (int) get_post_meta( $post_id, '_wpftw_ups', true ) );
$downs = max( 0, (int) get_post_meta( $post_id, '_wpftw_downs', true ) );
$vote = (int) get_post_meta(
$post_id, '_wpftw_vote_user_' . get_current_user_id(), true
);
echo '<div class="wpftw-vote" data-post-id="' . esc_attr( $post_id ) . '">';
printf(
'<button type="button" data-direction="1" aria-pressed="%s">Up</button>',
$vote === 1 ? 'true' : 'false'
);
echo '<span class="wpftw-vote-score">' . esc_html( $ups - $downs ) . '</span>';
printf(
'<button type="button" data-direction="-1" aria-pressed="%s">Down</button>',
$vote === -1 ? 'true' : 'false'
);
echo '</div>';
}
This example hides the controls from signed-out visitors. That keeps the identity model simple while you learn the flow. If you want guest voting, an IP address alone is not a reliable one-person-one-vote key: shared networks, proxies, and changing addresses make it imperfect.
2. Send the vote without reloading the page
Enqueue one JavaScript file and give it the WordPress AJAX URL plus a nonce. The browser sends the post ID and direction, then replaces the visible score with the server’s answer. Clicking the same direction again removes that vote.
add_action( 'wp_enqueue_scripts', 'wpftw_enqueue_vote_script' );
function wpftw_enqueue_vote_script() {
if ( ! function_exists( 'bbp_get_topic_id' ) ) {
return;
}
wp_enqueue_script(
'wpftw-vote',
plugin_dir_url( __FILE__ ) . 'wpftw-vote.js',
array(),
'1.0',
true
);
wp_localize_script( 'wpftw-vote', 'wpftwVote', array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wpftw_vote' ),
) );
wp_enqueue_style(
'wpftw-vote', plugin_dir_url( __FILE__ ) . 'wpftw-vote.css',
array(), '1.0'
);
}
// wpftw-vote.js
document.addEventListener('click', async (event) => {
const button = event.target.closest('.wpftw-vote button[data-direction]');
if (!button) return;
const wrapper = button.closest('.wpftw-vote');
const buttons = wrapper.querySelectorAll('button');
buttons.forEach((item) => { item.disabled = true; });
const data = new FormData();
data.set('action', 'wpftw_cast_vote');
data.set('nonce', wpftwVote.nonce);
data.set('post_id', wrapper.dataset.postId);
data.set('direction', button.dataset.direction);
try {
const response = await fetch(wpftwVote.ajaxUrl, {
method: 'POST', body: data, credentials: 'same-origin'
});
const result = await response.json();
if (!response.ok || !result.success) throw new Error('Vote not saved');
wrapper.querySelector('.wpftw-vote-score').textContent = result.data.score;
buttons.forEach((item) => {
item.setAttribute('aria-pressed',
Number(item.dataset.direction) === result.data.direction ? 'true' : 'false'
);
});
} catch (error) {
window.alert('The vote could not be saved. Please try again.');
} finally {
buttons.forEach((item) => { item.disabled = false; });
}
});
/* wpftw-vote.css */
.wpftw-vote { display: inline-flex; align-items: center; gap: .5rem; }
.wpftw-vote-score { min-width: 2ch; text-align: center; font-weight: 700; }
.wpftw-vote button[aria-pressed="true"] { font-weight: 700; outline: 2px solid currentColor; }
.wpftw-vote button:disabled { opacity: .5; }
3. Validate and store the vote on the server
The handler verifies the nonce, requires a signed-in user, and accepts only published bbPress topics or replies. It reads that user’s previous direction, subtracts the old vote, adds the new one, then returns fresh totals. The previous version of this tutorial got vote reversal wrong; switching from Up to Down must decrement Up and increment Down.
add_action( 'wp_ajax_wpftw_cast_vote', 'wpftw_cast_vote' );
function wpftw_cast_vote() {
check_ajax_referer( 'wpftw_vote', 'nonce' );
if ( ! function_exists( 'bbp_get_topic_post_type' ) ) {
wp_send_json_error( array( 'message' => 'bbPress is inactive.' ), 503 );
}
if ( ! is_user_logged_in() ) {
wp_send_json_error( array( 'message' => 'Sign in to vote.' ), 403 );
}
$post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
$direction = isset( $_POST['direction'] ) ? (int) $_POST['direction'] : 0;
if ( ! $post_id || ! in_array( $direction, array( 1, -1 ), true )
|| ! in_array( get_post_type( $post_id ), array(
bbp_get_topic_post_type(), bbp_get_reply_post_type()
), true ) || get_post_status( $post_id ) !== 'publish' ) {
wp_send_json_error( array( 'message' => 'Invalid vote.' ), 400 );
}
$key = '_wpftw_vote_user_' . get_current_user_id();
$old = (int) get_post_meta( $post_id, $key, true );
$new = $old === $direction ? 0 : $direction;
$ups = max( 0, (int) get_post_meta( $post_id, '_wpftw_ups', true ) );
$downs = max( 0, (int) get_post_meta( $post_id, '_wpftw_downs', true ) );
if ( $old === 1 ) { $ups = max( 0, $ups - 1 ); }
if ( $old === -1 ) { $downs = max( 0, $downs - 1 ); }
if ( $new === 1 ) { $ups++; }
if ( $new === -1 ) { $downs++; }
update_post_meta( $post_id, $key, $new );
update_post_meta( $post_id, '_wpftw_ups', $ups );
update_post_meta( $post_id, '_wpftw_downs', $downs );
update_post_meta( $post_id, '_wpftw_score', $ups - $downs );
wp_send_json_success( array(
'score' => $ups - $downs, 'ups' => $ups,
'downs' => $downs, 'direction' => $new,
) );
}
The state transitions are worth testing explicitly: no vote → Up is +1; Up → none is back to zero; Up → Down is -1; Down → Up is +1. This post-meta approach is educational, but two requests at the same instant can overwrite each other. For a high-traffic forum, use an atomic storage design and test caching and abuse controls before calling it production-ready.
4. Sort topics by score
We also save _wpftw_score after every vote. Here is a standalone topic query ordered by that value. It demonstrates the sorting piece; to change bbPress’s own forum loop, integrate the same meta key and ordering into that loop’s query arguments. Topics without a saved score may be omitted by a meta-key query, so initialize the key to zero when creating a topic or account for those topics in your query.
$topics = new WP_Query( array(
'post_type' => bbp_get_topic_post_type(),
'post_status' => 'publish',
'posts_per_page' => 20,
'meta_key' => '_wpftw_score',
'orderby' => 'meta_value_num',
'order' => 'DESC',
) );
Raw Up minus Down is a simple starting point. More advanced ranking can use a Wilson lower-bound score so a handful of votes do not outrank a much larger sample on percentage alone. If you calculate and store that score yourself, use the same descending numeric sort with its own meta key. That is separate from the basic implementation above.
// Optional: compute a Wilson lower bound (95% two-sided confidence).
function wpftw_wilson_lower_bound( int $ups, int $downs ): float {
$n = $ups + $downs;
if ( $n === 0 ) { return 0.0; }
$z = 1.96;
$p = $ups / $n;
$z2 = $z * $z;
return max( 0.0, (
$p + $z2 / ( 2 * $n )
- $z * sqrt( ( $p * ( 1 - $p ) + $z2 / ( 4 * $n ) ) / $n )
) / ( 1 + $z2 / $n ) );
}
If you opt into this ranking, add the following line inside wpftw_cast_vote(), after updating the vote counts and before wp_send_json_success():
update_post_meta( $post_id, '_wpftw_wilson', wpftw_wilson_lower_bound( $ups, $downs ) );
To query by Wilson score, change the query’s meta_key to _wpftw_wilson; keep orderby as meta_value_num and order as DESC. Initialize that key for existing topics too. This does not automatically change bbPress’s own sorting controls.
The easier way: install the plugin
You can build and maintain these pieces yourself. If you just want voting running, install my free bbPress Voting plugin instead. It handles the voting UI and AJAX flow for topics and replies, supports guest voting subject to its settings, and offers score sorting. Start there if the implementation is not the part of your forum you want to spend time maintaining.
For Q&A features beyond basic voting, bbPress Voting Pro adds accepted answers, who-voted avatars, weighted and trending ranking options, a sort dropdown, and Q&A schema. It runs alongside the free plugin. Accepted answers are marked and linked; they are not automatically pinned to the top, and search appearance is always Google’s decision. See the free-versus-Pro guide if you are deciding whether to upgrade.
Want someone to configure or customize the forum with you? Tell me about the project for an estimate.
Related Posts:
Blogger, expert WordPress developer, and developer of the awesome bbPress Voting plugin which is a must-have plugin for any bbPress forum.
Download bbPress Voting for free on the WordPress Plugin Directory.


