Created
June 30, 2011 20:21
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |
If you used the latter, PHP would throw an error when it encountered $this.
Yeah, so you could replace $this
with self
or __CLASS__
and make all the properties and methods static.
Yeah, so you could replace
$this
withself
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.
Can't argue with that. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's so that other people can access the singleton object and remove its filters, without having to have yet another global variable hanging around. The code is completely encapsulated within the class.
Those two are not equivalent. The former calls a method on an object. The latter calls a method on a class. If you used the latter, PHP would throw an error when it encountered
$this
. This is a singleton object that has been instantiated. We want to access that object, its methods, and its properties.