Created
April 10, 2014 04:38
-
-
Save andreisebastianc/10342955 to your computer and use it in GitHub Desktop.
Wordpress helper class for paged querying
This file contains hidden or 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 | |
/** | |
* | |
*/ | |
class PagedResourceQuery | |
{ | |
public static $cachedQueries = array(); | |
public static $supportedQueries = array( | |
"events" => array( | |
'post_type' => 'events', | |
'post_status' => 'publish', | |
'suppress_filters' => false, | |
'order' => 'ASC' | |
), | |
"news" => array( | |
'meta_key' => 'post_display_flag', | |
'post_type' => 'news', | |
'post_status' => 'publish', | |
'posts_per_page' => -1, | |
'orderby' => 'meta_value_num', | |
'suppress_filters' => false, | |
'order' => 'ASC' | |
) | |
); | |
public static function query($resource, $start = 0, $end = 5) | |
{ | |
$args = self::$supportedQueries[$resource]; | |
$args['posts_per_page'] = $end - $start; | |
$args['paged'] = $start; | |
return new WP_Query($args); | |
} | |
public static function get($resource, $start = 0, $end = 5) | |
{ | |
// cache here | |
$res = self::query($resource, $start, $end); | |
return $res->get_posts(); | |
} | |
public static function json($resource, $start = 0, $end = 5, $preprocessor =null) | |
{ | |
// cache here | |
$result = self::query($resource, $start, $end); | |
if (isset($preprocessor) && is_callable($preprocessor)) { | |
$result = call_user_func($preprocessor, $result->posts); | |
} else { | |
$result = $result->posts; | |
} | |
return json_encode($result); | |
} | |
} | |
function eventsToJSON ($array) { | |
$res = array(); | |
$temp = array(); | |
for ($i = 0; $i < count($array); $i++) { | |
$v = $array[$i]; | |
$meta = get_post_meta($v->ID); | |
$temp['post_title'] = $v->post_title; | |
$temp['meta'] = $meta; | |
$res[] = $temp; | |
} | |
return $res; | |
} | |
//print_r(PagedResourceQuery::json('news',0,5, 'eventsToJSON')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment