| 1 |
<?php |
| 2 |
/** |
| 3 |
* Query functions |
| 4 |
* |
| 5 |
* @package wpstream-theme |
| 6 |
*/ |
| 7 |
|
| 8 |
if ( ! function_exists( 'wpstream_custom_query' ) ) { |
| 9 |
/** |
| 10 |
* Perform a custom query with optional transient caching. |
| 11 |
* |
| 12 |
* @param array $query_args Query arguments. |
| 13 |
* @param string $transient_key Transient key for caching. |
| 14 |
* @param bool $use_transient Whether to use transient caching. Default is false. |
| 15 |
* |
| 16 |
* @return WP_Query|array|null The query result. |
| 17 |
*/ |
| 18 |
function wpstream_custom_query( $query_args, $transient_key, $use_transient = false ) { |
| 19 |
// Check if transient caching is enabled and post type is not "post". |
| 20 |
if ( $use_transient ) { |
| 21 |
// Try to get the data from the transient cache. |
| 22 |
$query = get_transient( $transient_key ); |
| 23 |
|
| 24 |
if ( false !== $query ) { |
| 25 |
return $query; // Return cached query result if available. |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
// If not using transient caching or cache is not available, proceed with the query. |
| 30 |
$query_args['ignore_sticky_posts'] = 1; |
| 31 |
if ( ! isset( $query_args['s'] ) ) { |
| 32 |
$query_args['post__not_in'] = array( get_the_ID() ); |
| 33 |
} |
| 34 |
$query = new WP_Query( $query_args ); |
| 35 |
|
| 36 |
// Check if the query has posts. |
| 37 |
if ( $query->have_posts() ) { |
| 38 |
if ( $use_transient ) { |
| 39 |
set_transient( $transient_key, $query, 6 * 60 * 60 ); |
| 40 |
} |
| 41 |
} else { |
| 42 |
delete_transient( $transient_key ); |
| 43 |
} |
| 44 |
wp_reset_postdata(); |
| 45 |
return $query; |
| 46 |
} |
| 47 |
} |
| 48 |
|