Make WordPress Core

Ticket #14349: wp-query-manipulation.php

File wp-query-manipulation.php, 1.4 KB (added by scribu, 16 years ago)
Line 
1<?php
2
3class WP_Query_Manipulation {
4
5 private $bits = array();
6 private $wp_query;
7
8 function __construct( $callback ) {
9
10 $this->callback = $callback;
11
12 $filters = array(
13 'posts_where',
14 'posts_join',
15 'posts_groupby',
16 'posts_orderby',
17 'posts_distinct',
18 'post_limits',
19 'posts_fields'
20 );
21
22 foreach ( $filters as $filter ) {
23 add_filter( $filter, array( $this, 'collect' ), 999, 2 );
24 add_filter( $filter . '_request' , array( $this, 'update' ), 9 );
25 }
26
27 add_action( 'posts_selection' , array( $this, 'alter' ) );
28 }
29
30 function collect( $value, $wp_query ) {
31 // remove 'posts_'
32 $key = explode( '_', current_filter() );
33 $key = array_slice( $key, 1 );
34 $key = implode( '_', $key );
35
36 $this->bits[ $key ] = $value;
37
38 $this->wp_query = $wp_query;
39
40 return $value;
41 }
42
43 function alter($query) {
44 $this->bits = call_user_func( $this->callback, $this->bits, $this->wp_query );
45 }
46
47 function update( $value ) {
48 // remove 'posts_' and '_request'
49 $key = explode( '_', current_filter() );
50 $key = array_slice( $key, 1, -1 );
51 $key = implode( '_', $key );
52
53 return $this->bits[ $key ];
54 }
55}
56
57
58// TESTING
59function test_wp_query_manipulation( $bits, $wp_query ) {
60 foreach ( $bits as $key => &$value )
61 $value = "[$key]";
62
63 return $bits;
64}
65new WP_Query_Manipulation( 'test_wp_query_manipulation' );
66
67function debug_wp_query_manipulation() {
68 var_dump( $GLOBALS['wp_query']->request );
69}
70add_filter( 'the_posts', 'debug_wp_query_manipulation' );
71