Completed
Push — master ( bc6754...ed64c2 )
by
unknown
07:19
created

Query_Helper::get_current_query()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 5
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 11
rs 9.4285
1
<?php
2
namespace Classy;
3
4
class Query_Helper {
5
6
	/**
7
	 * Finds or creates new query based on provided params
8
	 *
9
	 * @param  array|boolean $args
10
	 * @return object        WP_Query
11
	 */
12
	public static function find_query( $args = false ) {
13
14
		$default_args = array();
15
16
		if ( ! $args ) {
17
18
			return self::get_current_query();
19
20
		} elseif ( is_array( $args ) ) {
21
22
			$args = array_merge( $default_args, $args );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $args. This often makes code more readable.
Loading history...
23
24
			return new \WP_Query( $args );
25
26
		} else {
27
28
			return new \WP_Query( $default_args );
29
30
		}
31
	}
32
33
	/**
34
	 * Returns current WP_Query
35
	 *
36
	 * @return object WP_Query
37
	 */
38
	public static function get_current_query() {
39
40
		global $wp_query;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
41
42
		$query =& $wp_query;
43
44
		$query = self::handle_maybe_custom_posts_page( $query );
45
46
		return $query;
47
48
	}
49
50
	/**
51
	 * Checks and returns WP_Query for home posts page
52
	 *
53
	 * @param  object $query WP_Query
54
	 * @return object        WP_Query
55
	 */
56
	private static function handle_maybe_custom_posts_page( $query ) {
57
58
		if ( $custom_posts_page = get_option( 'page_for_posts' ) ) {
59
60
			if ( isset( $query->query['p'] ) && absint( $query->query['p'] ) === absint( $custom_posts_page ) ) {
61
62
				return new \WP_Query( array( 'post_type' => 'post' ) );
63
64
			}
65
		}
66
67
		return $query;
68
69
	}
70
}
71