“Posts per page” dropdown for BuddyPress single forum topic view

This morning I whipped up a little BuddyPress ditty for the CUNY Academic Commons that allows your members to select how many posts they’d like to see at a time when viewing a single forum topic. It’s not particularly beautiful (for one thing, it requires Javascript to work correctly, though it degrades gracefully by not showing up when no jQuery is available). For that reason, it’s probably not really appropriate for distribution in BuddyPress itself, at least not without some heavy cleanup. Anyway, here it is:

In your theme’s functions.php, place the following function:


/**
 * Echoes the markup for the "number of posts per page" dropdown on forum topics
 */
function cac_forums_show_per_page_dropdown() {
	global $topic_template;

	// Get the current number, so we can preselect the dropdown
	$selected = in_array( $topic_template->pag_num, array( 5, 15, 30 ) ) ? $topic_template->pag_num : $topic_template->total_post_count;

	// Inject the javascript
	?>
	<script type="text/javascript">
	jQuery(document).ready( function() {
		jQuery('div#posts-per-page-wrapper').show();
		jQuery('select#posts-per-page').change(function(){
			var url = '<?php bp_the_topic_permalink() ?>?topic_page=1&amp;num=' + jQuery(this).val();
			window.location = url;
		});
	});
	</script>

	<?php // Now create the markup ?>

	<div id="posts-per-page-wrapper">Posts per page:
		<select name="posts-per-page" id="posts-per-page">
			<option value="5" <?php selected( $selected, 5 ) ?>> 5 </option>
			<option value="15" <?php selected( $selected, 15 ) ?>> 15 </option>
			<option value="30"  <?php selected( $selected, 30 ) ?>> 30 </option>
			<option value="<?php echo $topic_template->total_post_count ?>"  <?php selected( $selected, $topic_template->total_post_count ) ?>> All </option>
		</select>
	</div>

	<?php
}

Then you’ll have to call the function somewhere in your template. I chose to put mine in groups/forum/topic.php, right after the Leave A Reply button:


<?php cac_forums_show_per_page_dropdown() ?>

Finally, you’ll probably want to add some styles to your stylesheet. In particular, you’ll want to ensure that the dropdown doesn’t show up for users who have JS turned off. Here are the styles I’m using; adjust them to your taste.


div#posts-per-page-wrapper {
	display: none;
	position: absolute;
	right: 0;
	top: 0;
	font-size: 11px;
	color: #888;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image