alleyinteractive / archiveless

WordPress plugin to hide posts from archives (lists)
GNU General Public License v2.0
7 stars 4 forks source link

Handling `archiveless` posts in REST API queries #61

Closed renatonascalves closed 10 months ago

renatonascalves commented 11 months ago

Description

I think there is a reasonable expectation that this plugin would not impact the site's admin, where editors would need access to all posts, archived or not.

This doesn't happen automatically. It's currently the responsibility of site admins to fix regressions, a feature?, added by the Archiveless plugin.

Take the Page Attributes feature as an example. This plugin removes the archived pages from that list since the REST API query performed is the default query with params.

The same is true for the other parts of the WordPress back-end, like page lists and dropdowns, quick and bulk edits, etc.


One problem we have here is that there needs to be more context about where the REST API request comes from. We can confirm the user's capability, but not that the request is coming from a Slotfill for the Page Attributes in a specific post type.

The REST API, however, provides a context param.

The edit context is used to make the response include the fields needed to edit the resource. So, the edit context is always used when doing GET requests to obtain the data for editing.

Source.

That means we can reasonably assume that REST API requests using the edit context, in the back-end or front-end of the site, are being performed for editing purposes, where we want to show the archived posts.

Here is some pseudocode of what I'm suggesting.

/**
 * Filter the query to include `archiveless` posts.
 *
 * @param array           $args    Array of arguments for WP_Query.
 * @param WP_REST_Request $request The REST API request.
 * @return array
 */
function filter_query_parent_posts( $args, $request ): array {
    // Check the edit context from WP_REST_Request.
    if ( 'edit' !== $request->get_param( 'context' ) ) {
        return $args;
    }

    $args['include_archiveless'] = true;

    return $args;
}
add_filter( 'rest_page_query', 'filter_query_parent_posts', 10, 2 );

Use Case

This bug recently affected a client site. The client has a post type where they can't select the parent post in the Page Attributes slotfill because the archived parent doesn't appear in the results list.