Skip to content

Commit

Permalink
Fix Product Query block hijacking all Query blocks queries (woocommer…
Browse files Browse the repository at this point in the history
…ce#6952)

* Fix Product Query block hijacking all Query blocks queries

The Product Query block was adding a filter to Gutenberg's core
Query Loop block. When this filter was added once, it would from
then on apply to all other Query Loop blocks (or variations thereof)
on a page.

This change makes sure that:

1. No filters are added in the first place if our custom `__woocommerceVariationProps`
are not set.
2. The filter only gets run once.
  • Loading branch information
sunyatasattva authored and senadir committed Nov 12, 2022
1 parent be1ab64 commit 69044c8
Showing 1 changed file with 34 additions and 5 deletions.
39 changes: 34 additions & 5 deletions src/BlockTypes/ProductQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ class ProductQuery extends AbstractBlock {
*/
protected $block_name = 'product-query';

/**
* The Block with its attributes before it gets rendered
*
* @var array
*/
protected $parsed_block;

/**
* Initialize this block type.
*
Expand All @@ -30,24 +37,46 @@ protected function initialize() {

}

/**
* Remove the query block filter and parse the custom query
*
* This function is supposed to be called by the `gutenberg_build_query_vars_from_query_block`
* filter. It de-registers the filter to make sure it runs only once and doesn't end
* up hi-jacking future Query Loop blocks.
*
* It needs unfortunately to be `public` or otherwise the filter can't call it.
*
* @param WP_Query $query The WordPress Query.
* @return array
*/
public function get_query_by_attributes_once( $query ) {
remove_filter(
'gutenberg_build_query_vars_from_query_block',
array( $this, 'get_query_by_attributes_once' ),
10
);

return $this->get_query_by_attributes( $query, $this->parsed_block );
}

/**
* Update the query for the product query block.
*
* @param string|null $pre_render The pre-rendered content. Default null.
* @param array $parsed_block The block being rendered.
*/
public function update_query( $pre_render, $parsed_block ) {
if ( 'core/query' !== $parsed_block['blockName'] ) {
if ( 'core/query' !== $parsed_block['blockName'] || ! isset( $parsed_block['attrs']['__woocommerceVariationProps'] ) ) {
return;
}

$this->parsed_block = $parsed_block;

add_filter(
'gutenberg_build_query_vars_from_query_block',
function( $query ) use ( $parsed_block ) {
return $this->get_query_by_attributes( $query, $parsed_block );
},
array( $this, 'get_query_by_attributes_once' ),
10,
3
1
);
}

Expand Down

0 comments on commit 69044c8

Please sign in to comment.