BlockHooksTrait.php
4 weeks ago
BlockTemplateUtils.php
2 months ago
BlocksSharedState.php
3 months ago
BlocksWpQuery.php
2 years ago
CartCheckoutUtils.php
4 weeks ago
MiniCartUtils.php
1 year ago
ProductAvailabilityUtils.php
11 months ago
ProductDataUtils.php
1 year ago
ProductGalleryUtils.php
4 weeks ago
StyleAttributesUtils.php
1 year ago
Utils.php
2 years ago
BlocksWpQuery.php
72 lines
| 1 | <?php |
| 2 | namespace Automattic\WooCommerce\Blocks\Utils; |
| 3 | |
| 4 | use WP_Query; |
| 5 | |
| 6 | /** |
| 7 | * BlocksWpQuery query. |
| 8 | * |
| 9 | * Wrapper for WP Query with additional helper methods. |
| 10 | * Allows query args to be set and parsed without doing running it, so that a cache can be used. |
| 11 | * |
| 12 | * @deprecated 2.5.0 |
| 13 | */ |
| 14 | class BlocksWpQuery extends WP_Query { |
| 15 | /** |
| 16 | * Constructor. |
| 17 | * |
| 18 | * Sets up the WordPress query, if parameter is not empty. |
| 19 | * |
| 20 | * Unlike the constructor in WP_Query, this does not RUN the query. |
| 21 | * |
| 22 | * @param string|array $query URL query string or array of vars. |
| 23 | */ |
| 24 | public function __construct( $query = '' ) { |
| 25 | if ( ! empty( $query ) ) { |
| 26 | $this->init(); |
| 27 | $this->query = wp_parse_args( $query ); |
| 28 | $this->query_vars = $this->query; |
| 29 | $this->parse_query_vars(); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Get cached posts, if a cache exists. |
| 35 | * |
| 36 | * A hash is generated using the array of query_vars. If doing custom queries via filters such as posts_where |
| 37 | * (where the SQL query is manipulated directly) you can still ensure there is a unique hash by injecting custom |
| 38 | * query vars via the parse_query filter. For example: |
| 39 | * |
| 40 | * add_filter( 'parse_query', function( $wp_query ) { |
| 41 | * $wp_query->query_vars['my_custom_query_var'] = true; |
| 42 | * } ); |
| 43 | * |
| 44 | * Doing so won't have any negative effect on the query itself, and it will cause the hash to change. |
| 45 | * |
| 46 | * @param string $transient_version Transient version to allow for invalidation. |
| 47 | * @return WP_Post[]|int[] Array of post objects or post IDs. |
| 48 | */ |
| 49 | public function get_cached_posts( $transient_version = '' ) { |
| 50 | $hash = md5( wp_json_encode( $this->query_vars ) ); |
| 51 | $transient_name = 'wc_blocks_query_' . $hash; |
| 52 | $transient_value = get_transient( $transient_name ); |
| 53 | |
| 54 | if ( isset( $transient_value, $transient_value['version'], $transient_value['value'] ) && $transient_value['version'] === $transient_version ) { |
| 55 | return $transient_value['value']; |
| 56 | } |
| 57 | |
| 58 | $results = $this->get_posts(); |
| 59 | |
| 60 | set_transient( |
| 61 | $transient_name, |
| 62 | array( |
| 63 | 'version' => $transient_version, |
| 64 | 'value' => $results, |
| 65 | ), |
| 66 | DAY_IN_SECONDS * 30 |
| 67 | ); |
| 68 | |
| 69 | return $results; |
| 70 | } |
| 71 | } |
| 72 |