> For the complete documentation index, see [llms.txt](https://whoisandywhite.gitbook.io/porterwp/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://whoisandywhite.gitbook.io/porterwp/developer-api/porter-query-filter-base.md). Agents can also search and read this documentation through its [MCP server](https://whoisandywhite.gitbook.io/porterwp/~gitbook/mcp).

# Porter\_QueryFilter\_Base

`Porter_QueryFilter_Base` is a theme-facing helper for modifying a specific non-inherited Query Loop and, when explicitly allowed, the front-end main query. It centralises block matching, query scoping, empty-search cleanup, and optional debugging.

The behavior documented here applies to PorterWP 1.4.95.

## Location

* `includes/helpers/class-Porter_QueryFilter_Base.php`
* Loaded automatically by `includes/porter-helper-functions.php`

## Minimum implementation

```php
class Porter_Filter_UpcomingEvents extends Porter_QueryFilter_Base {
    protected string $className = 'upcoming-events';

    protected function should_apply_to_main( WP_Query $query ): bool {
        return $query->is_post_type_archive( 'event' )
            || $query->is_tax( [ 'event-type', 'event-format' ] );
    }

    protected function filter_args( array $args, array $context ): array {
        $args['post_type']   = 'event';
        $args['post_status'] = [ 'publish' ];
        $args['meta_key']    = 'start_date';
        $args['orderby']     = 'meta_value_num';
        $args['order']       = 'ASC';

        if ( is_singular( 'event' ) ) {
            $args['post__not_in'] = [ get_the_ID() ];
        }

        return $args;
    }
}

new Porter_Filter_UpcomingEvents();
```

Instantiate a subclass once, normally from a file under `porter/inc/`.

## Subclass API

| Member                                              | Required               | Purpose                                                                                                          |
| --------------------------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `$className`                                        | Yes in normal use      | Exact CSS class token that activates this filter on the target block. An empty value matches every target block. |
| `filter_args( array $args, array $context ): array` | Yes                    | Return the amended query variables.                                                                              |
| `should_apply_to_main( WP_Query $query ): bool`     | For main-query changes | Explicitly allow the filter on the current front-end main query. The default is `false`.                         |
| `treat_post_type_change_as_real(): bool`            | No                     | Decide whether a post-type-only difference is meaningful on the main query. The default is `true`.               |
| `$blockName`                                        | No                     | Target block name. The default is `core/query`.                                                                  |

The property and method signatures used by existing subclasses are unchanged in 1.4.95.

## Hook timing

The constructor installs three stable hooks immediately:

| Hook                          | Priority | Purpose                                                               |
| ----------------------------- | -------: | --------------------------------------------------------------------- |
| `pre_get_posts`               |       20 | Apply an explicitly permitted main-query filter before blocks render. |
| `pre_render_block`            |       15 | Detect a matching target block and capture its `queryId`.             |
| `query_loop_block_query_vars` |       10 | Apply the non-inherited block query changes.                          |

Main queries are prepared before a template's blocks render. Registering `pre_get_posts` in the constructor is therefore essential; waiting until a matching inherited block is rendered is too late.

## Non-inherited Query Loops

For a target block such as `core/query`, PorterWP splits `className` on whitespace and requires `$className` to be an exact token. For example, `upcoming-events` matches:

```
cards upcoming-events has-dividers
```

It does not match `upcoming-events-grid`.

When the block is non-inherited, PorterWP captures its integer `queryId`. The query-variable filter runs only when the `WP_Block` context contains that same ID. The stored ID is reset whenever another target block is inspected, so a previous match cannot leak into an unrelated Query Loop.

The cleaned query variables are passed to `filter_args()` and its returned array becomes the block query. An empty `s` value is removed both before and after the subclass runs.

## Inherited and main queries

`pre_get_posts` considers only a non-admin main query. It calls `should_apply_to_main()` first and does nothing unless the subclass returns `true`.

This decision is request-based, not block-based: the main query already exists before WordPress renders the inherited Query Loop. Make `should_apply_to_main()` as narrow as possible by checking the intended archive, taxonomy, search, or other request condition.

When allowed, PorterWP:

1. removes an empty search value;
2. passes the current `query_vars` to `filter_args()`;
3. compares the original and amended arrays;
4. removes keys that the subclass removed and sets keys it added or changed;
5. clears the `is_search` flag when no real search value remains.

If there are no meaningful changes, it leaves the query alone apart from cleaning the empty search value and false search state. Override `treat_post_type_change_as_real()` to return `false` only when changing `post_type` by itself should not cause the main-query amendment to be applied.

## `filter_args()` context

The second argument describes which path is running:

| Key        | Block query         | Main query         |
| ---------- | ------------------- | ------------------ |
| `scope`    | `'block'`           | `'main'`           |
| `block`    | Matching `WP_Block` | `null`             |
| `wp_query` | `null`              | Current `WP_Query` |

One subclass can therefore share common arguments while branching where the two query paths need different behavior:

```php
protected function filter_args( array $args, array $context ): array {
    $args['post_type'] = 'event';

    if ( 'block' === $context['scope'] ) {
        $args['posts_per_page'] = 6;
    }

    return $args;
}
```

## Usage checklist

1. Add a distinctive CSS class to the intended Query Loop block.
2. Set `$className` to that exact class token.
3. Implement `filter_args()` with valid `WP_Query` variables.
4. Override `should_apply_to_main()` only if the same class must modify a front-end main query.
5. Instantiate the subclass once.

Do not leave `$className` empty unless the intentional result is to target every block named by `$blockName`.

## Debugging

Define the following only in a development environment:

```php
define( 'PORTER_QUERY_FILTER_DEBUG', true );
```

This enables before/after difference logging and the verbose internal trace. Entries are prefixed with `[PorterQueryDbg]` and the concrete subclass name. Query variables can contain request-specific data, so avoid enabling the trace on production sites for routine use.

## Migrating to 1.4.95

* Existing subclasses, method signatures, and typed properties continue to work.
* Class matching is now an exact whitespace-delimited token rather than a substring search. If an older integration relied on `events` matching `events-grid`, add the exact `events` class to the block or update `$className` to `events-grid`.
* `pre_get_posts` is registered when the subclass is constructed. Keep the `should_apply_to_main()` condition narrow; it no longer depends on a block render occurring first.
* A removed query key is now removed from the main `WP_Query`, not silently retained. Review subclasses that intentionally return a reduced argument array.
* `PORTER_QUERY_FILTER_DEBUG` now enables the full trace as well as compact difference output.
