Opened 13 years ago
Closed 12 years ago
#19041 closed enhancement (wontfix)
function to list all (true) conditionals (in an array)
Reported by: |
|
Owned by: |
|
---|---|---|---|
Milestone: | Priority: | normal | |
Severity: | normal | Version: | 3.3 |
Component: | Query | Keywords: | has-patch |
Focuses: | Cc: |
Description
Often we need to check against a lot of conditionals. It would be handy to have one "mother" function to retrieve those query conditionals that are set true with a single call.
The attached patch introduces a new function get_conditionals();
that returns a numerical indexed array containing all object parts of $GLOBALS['wp_query'];
that start with is_
and are set to true.
Attachments (1)
Change History (9)
#3
in reply to:
↑ 2
@
13 years ago
Replying to johnbillion:
Can you post a code snippet where use of this function saves code?
I currently use it in two classes (breadcrumbs & pagination) for function routing/name guessing. It lets me avoid long if/elseif/else
statements and long switch( $case )
statements.
$output = array(); foreach ( get_conditionals() as $conditional ) { // Can catch everything using a simple string replace: $fn_name = str_replace( 'is_', 'get_', $conditional ); if ( method_exists( __CLASS__, $fn_name ) ) $output[] = $this->$fn_name( $args ); }
If someone is not so much into consistant naming, it wouldn't help too much. I'm sure there are other use cases that I'm currently not aware of, but it's a public API extension that doesn't hurt if you don't use it.
#5
@
13 years ago
On the one hand, I also have a function that does something very similar, so I know that this would be useful at least to some people. On the other hand, it's pretty easy to implement outside of Core.
There are a few problems with the patch:
- it only works on the main WP_Query instance; it should be a WP_Query method instead.
- it uses preg_match(), when a simple
'is_' == substr( $key, 0, 3 )
would do. - it casts WP_Query to an array, instead of using get_object_vars().
#6
follow-up:
↓ 7
@
13 years ago
For reference, here's how I do it:
// Returns an array containing the flags that have been set function get_query_flags( $wp_query = null ) { if ( !$wp_query ) $wp_query = $GLOBALS['wp_query']; $flags = array(); foreach ( get_object_vars( $wp_query ) as $key => $val ) { if ( 'is_' == substr( $key, 0, 3 ) && $val ) $flags[] = substr( $key, 3 ); } return $flags; }
Local performance testing show that the needed time is between 0.00003 and 0.00013 seconds.