creative-andrew / single-post-query-loop-selector

A Query Loop block variation that allow to search and select a single post to be displayed.
7 stars 3 forks source link

fix: filter affecting other queries #4

Closed creative-andrew closed 7 months ago

creative-andrew commented 7 months ago

Closes https://github.com/creative-andrew/single-post-query-loop-selector/issues/1 Check: https://github.com/WordPress/gutenberg/issues/60295

While working on this I noticed a couple of things.

The query_loop_block_query_vars filter’s $block param doesn’t pass the variation itself. So it’s not possible to check 'creativeandrew/single-post-query-loop-selector' === $block->parsed_block['attrs']['namespace'] That might explain why in the documentation it is mentioned the need to have access to the pre_render_block. I was able to avoid my filter from being applied to other queries by comparing the queryId from the one coming from the pre_render_block and query_loop_block_query_vars

function pre_render_block( $pre_render, $parsed_block ) {
    if ( isset( $parsed_block['attrs']['namespace'] )
    && 'creativeandrew/single-post-query-loop-selector' === $parsed_block['attrs']['namespace'] ) {
        add_filter(
            'query_loop_block_query_vars',
            function ( $default_query, $block ) use ( $parsed_block ) {
                if ( isset( $parsed_block['attrs']['query']['include'] )
                && isset( $block->context['queryId'] )
                && $block->context['queryId'] === $parsed_block['attrs']['queryId'] ) {
                    $default_query['post__in'] = $parsed_block['attrs']['query']['include'];
                }

                return $default_query;
            },
            10,
            2
        );

    }
    return $pre_render;
}