Skip to content

Instantly share code, notes, and snippets.

@markjaquith
Created June 30, 2011 20:21
Show Gist options
  • Save markjaquith/1057123 to your computer and use it in GitHub Desktop.
Save markjaquith/1057123 to your computer and use it in GitHub Desktop.
WordPress plugin example code to correctly set a custom number of posts to display per page, for specific types of views
<?php
/*
Plugin Name: CWS Posts Per Page
Version: 0.1
Description: Sets a custom number of posts to display per page, for specific types of views
Author: Mark Jaquith
Author URI: http://coveredwebservices.com/
*/
class CWS_Posts_Per_Page_Plugin {
public static $instance;
public $posts_per_page = array(
'day' => 9999,
'month' => 30,
'search' => 30,
'year' => 30,
'author' => 30,
'category' => 30,
);
public $ran = false;
public function __construct() {
self::$instance = $this;
// We use parse_request, because that only runs on primary WP queries. We use that to add the parse_query filter
add_action( 'parse_request', array( $this, 'parse_request' ) );
}
public function parse_request() {
add_action( 'parse_query', array( $this, 'parse_query' ) );
}
public function parse_query( $q ) {
if ( $this->ran )
return $q;
foreach ( $this->posts_per_page as $flag => $ppp ) {
$flag = 'is_' . $flag;
if ( $q->$flag ) {
$q->set( 'posts_per_page', $ppp );
break;
}
}
// If you want to add more logic, do it here
// Mark this code as having run, so it doesn't run more than once
$this->ran = true;
return $q;
}
}
new CWS_Posts_Per_Page_Plugin;
@markjaquith
Copy link
Author

Yeah, so you could replace $this with self or __CLASS__ and make all the properties and methods static.

Ah. Just a syntactic preference. self::$foo looks uglier and less familiar than $this->foo to me.

@scribu
Copy link

scribu commented Jul 1, 2011

Can't argue with that. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment