Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for post_types to rest api #59

Merged
merged 4 commits into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion config/post-meta.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"wp_curate_deduplication": {
"post_types": [
"post"
"all"
],
"type": "boolean"
}
Expand Down
43 changes: 43 additions & 0 deletions src/features/class-rest-api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
/**
* Rest_Api class file
*
* @package wp-curate
*/

namespace Alley\WP\WP_Curate\Features;

use Alley\WP\Types\Feature;

/**
* Look for a special query var that indicates a query should not run.
*/
final class Rest_Api implements Feature {
/**
* Set up.
*/
public function __construct() {}

/**
* Boot the feature.
*/
public function boot(): void {
add_filter( 'rest_post_query', [ $this, 'add_type_param' ], 10, 2 );
}

/**
* Add post_type to rest post query if the type param is set.
*
* @param array<array<int, string>|string> $query_args The existing query args.
* @param \WP_REST_Request $request The REST request.
* @return array<array<int, string>|string>
*/
public function add_type_param( $query_args, $request ): array { // @phpstan-ignore-line
if ( ! empty( $request->get_param( 'type' ) ) && is_string( $request->get_param( 'type' ) ) ) {
$types = explode( ',', $request->get_param( 'type' ) );
$types = array_filter( $types, 'post_type_exists' );
$query_args['post_type'] = $types;
}
return $query_args;
Comment on lines +28 to +41
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I get where this is coming from, but I'm concerned that it's not really the correct use of the REST API. It will cause the API to try to apply the schema for the post post type to posts from any post type, which might have unpredictable results. The search endpoint is more annoying to use but might be more correct for this case.

}
}
2 changes: 2 additions & 0 deletions src/main.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ function main(): void {
block_type_registry: WP_Block_Type_Registry::get_instance(),
);

$features[] = new Features\Rest_Api();

foreach ( $features as $feature ) {
$feature->boot();
}
Expand Down