List all conditionals that are true
As all is_*()
functions have their equivalent in a query variable (the functions are just wrappers), you can access them also another way: Get simply all that are true
.
I wrote a ticket on core/trac that adds a function to list them all.
In the meanwhile you can use both listed functions as helper plugins that show you on which request which conditional is available. It will print a var_dump()
below the footer (both admin & public) at the shutdown
hook.
<?php
/** Plugin Name: (#62232) »kaiser« List all conditionals that are true */
function get_conditionals()
{
global $wp_query;
foreach ( get_object_vars( $wp_query ) as $is_key => $is_value )
{
if ( $is_value && preg_match( "/is_/", $is_key ) )
$conditionals[] = $is_key;
}
return var_dump( $conditionals );
}
add_action( 'shutdown', 'get_conditionals' );
This way you can simply loop through them.
@scribu added his own function to the ticket (an interesting solution too).
<?php
/** Plugin Name: (#62232) »scribu« List all conditionals that are true */
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 var_dump( $flags );
}
add_action( 'shutdown', 'get_query_flags' );
Performance
I ran a performance test on each function in the middle of a template using timer_start/*_stop();
. TO be fair, I renamed all functions to a one character name a/b/c()
.
As you can see, Chips hard coded function is fastest, then goes mine and last is in this case scribus.
Update
If you know me, then you know my love for iterators for their elegance, clearness and their ability to hold only a single item in memory instead of of copy of a whole array while looping. So here's a quick custom class that extends a \FilterIterator
, therefore needing only a single method reworked.
<?php
namespace WPSE;
class ConditionalsFilter extends \FilterIterator
{
/**
* Accepts properties that start with `is_` and have a positive boolean value
* @return bool
*/
public function accept()
{
return 0 === strncasecmp( $this->key(), 'is_', 3 )
and filter_var(
$this->current(),
FILTER_VALIDATE_BOOLEAN,
FILTER_NULL_ON_FAILURE
);
}
}
It can be used quite easily. The $it->current()
holds the value, while $it->key()
returns the conditional/property name.
$cond = new WPSE\ConditionalsFilter( new \ArrayIterator(
get_object_vars( $GLOBALS['wp_query'] )
) );
foreach ( $cond as $c )
{
var_dump(
$cond->key(),
$cond->current()
);
}