So, all query conditionals (is_paged
, is_singular
, etc) look something like this:
function is_paged() {
global $wp_query;
if ( ! isset( $wp_query ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
return false;
}
return $wp_query->is_paged();
}
Globalize $wp_query
and call the corresponding method of the WP_Query object. In this case:
<?php
function is_paged() {
return (bool) $this->is_paged;
}
The only database hit you incur is from when the WP_Query object is created, which happens anyway.
Calling a function incurs a cost, so does using an if statement. Those costs on today’s hardware are nothing to really worry about.
That said, if you find yourself doing a lot of conditional checking using the same function, you’re probably better off to evaluate the control flow of your program.
Something like this:
<?php
if(is_paged() && 1 == get_query_var('some_query_var'))
{
// do stuff
}
else if(is_paged() && 2 == get_query_var('some_query_var'))
{
// do other stuff
}
Could become:
<?php
if(is_paged())
{
switch(get_query_var('some_query_var'))
{
case 1:
// do stuff
break;
case 2:
// do stuff
break;
default:
// do stuff
break;
}
}
As a final word of advice, I would “cache” results of conditionals (or any other function call, within reason) within the same function if you need them more than once, but I wouldn’t cache something like a object property unless you really need that persist from method to method.
Here’s a terrible example that (probably) doesn’t follow my advice above.
<?php
function wpse65916_stuff()
{
$paged = is_paged();
if($paged)
{
// do stuff because paged
}
if($paged && /* some other condition */)
{
// do stuff
}
}