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

WIP: Add post type and REST API controller #251

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 2 additions & 2 deletions blocks/query/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -180,12 +180,12 @@ export default function Edit({
if (postsToInclude.length > 0) {
validPosts = await apiFetch({
path: addQueryArgs(
'/wp/v2/posts',
'/wp/v2/wp-curate',
{
offset: 0,
orderby: 'include',
per_page: postsToInclude.length,
type: postTypeString,
post_type: postTypeString,
include: postsToInclude,
_locale: 'user',
context: 'edit',
Expand Down
4 changes: 2 additions & 2 deletions blocks/subquery/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -195,12 +195,12 @@ export default function Edit({
if (postsToInclude.length > 0) {
validPosts = await apiFetch({
path: addQueryArgs(
'/wp/v2/posts',
'/wp/v2/wp-curate',
{
offset: 0,
orderby: 'include',
per_page: postsToInclude.length,
type: postTypeString,
post_type: postTypeString,
include: postsToInclude,
_locale: 'user',
context: 'edit',
Expand Down
102 changes: 102 additions & 0 deletions src/features/class-curate-rest-controller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
<?php
/**
* Custom REST controller for the WP Curate post type.
*
* @package wp-curate
*/

namespace Alley\WP\WP_Curate\Features;

use WP_REST_Posts_Controller;
use WP_REST_Request;
use WP_Query;
use WP_REST_Response;
use WP_Error;
use WP_Post;

/**
* Extends the default posts controller to support multiple post types.
*/
class Curate_Rest_Controller extends WP_REST_Posts_Controller {
/**
* Constructor for the custom REST controller.
*/
public function __construct() {
parent::__construct('wp-curate');
}

/**
* Retrieves a collection of posts, supporting multiple post types.
*
* @param WP_REST_Request $request The REST request object.
* @return WP_REST_Response|WP_Error The response object or WP_Error.
*/
public function get_items( $request ) {
// Fetch allowed post types via filter, defaulting to 'post'.
$allowed_post_types = apply_filters('wp_curate_allowed_post_types', ['post']);

// Retrieve 'post_type' parameter and filter allowed post types.
$requested_types = $request->get_param('post_type');
$post_types = ! empty( $requested_types ) ? array_filter(
is_array($requested_types) ? $requested_types : explode(',', $requested_types),
function( $type ) use ( $allowed_post_types ) {
return in_array( $type, $allowed_post_types, true );
}
) : $allowed_post_types;

// Setup query arguments.
$args = [
'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => $request->get_param('per_page') ?: 2,
];

// Handle 'include' parameter for specific post IDs.
$include = $request->get_param('include');
if ( ! empty( $include ) ) {
// Ensure 'post__in' is an array of positive integers.
$args['post__in'] = array_map('absint', is_array( $include ) ? $include : explode( ',', $include ));

// Preserve the order of included posts.
$args['orderby'] = 'post__in';
}

// Execute the query with the defined arguments.
$query = new WP_Query( $args );
$posts = $query->posts;

// Return an empty response if no posts are found.
if ( empty( $posts ) ) {
return new WP_REST_Response( [] );
}

// Format the response data by preparing each post for the response.
$data = array_map( function( $post ) use ( $request ) {
$response = $this->prepare_item_for_response( $post, $request );
return $this->prepare_response_for_collection( $response );
}, $posts);

// Create the REST response with the formatted data.
$response = new WP_REST_Response( $data );
$response->header('X-WP-Total', $query->found_posts); // Add total number of posts found.
$response->header('X-WP-TotalPages', ceil( $query->found_posts / $args['posts_per_page'] )); // Add total number of pages.

return $response;
}

/**
* Prepares a single post for response.
*
* @param WP_Post $post The post object.
* @param WP_REST_Request $request The REST request object.
* @return WP_REST_Response The response object.
*/
public function prepare_item_for_response( $post, $request ) {
// Utilize the default controller to prepare the post for response.
$controller = new WP_REST_Posts_Controller( $post->post_type );
$response = $controller->prepare_item_for_response( $post, $request );

// Return an empty response if an error is encountered.
return is_wp_error( $response ) ? new WP_REST_Response([]) : $response;
}
}
29 changes: 27 additions & 2 deletions src/features/class-rest-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ public function __construct() {}
public function boot(): void {
add_action( 'rest_api_init', [ $this, 'register_endpoints' ] );
add_filter( 'rest_post_query', [ $this, 'add_type_param' ], 10, 2 );

// Register the wp-curate post type to be used for getting posts to the core Post Template block.
add_action( 'init', [ $this, 'register_post_type' ] );
}

/**
Expand Down Expand Up @@ -181,12 +184,34 @@ public function add_type_param( $query_args, $request ): array { // phpcs:ignore

$type = $request->get_param( 'type' );

// Handle the type parameter when it is a comma separated string of post types.
if ( ! empty( $type ) && is_string( $type ) ) {
$types = explode( ',', $type );
$types = array_filter( $types, 'post_type_exists' );
$types = explode(',', $type);

// Get the allowed post types.
$allowed_post_types = apply_filters('wp_curate_allowed_post_types', ['post']);

// Filter types against allowed post types and ensure they exist.
$types = array_filter( $types, function( $type ) use ( $allowed_post_types ) {
return in_array( $type, $allowed_post_types, true ) && post_type_exists( $type );
} );

$query_args['post_type'] = $types;
}

return $query_args;
}

/**
* Registers the wp-curate post type that serves as a proxy for our REST API endpoint.
*/
public function register_post_type(): void {
register_post_type('wp-curate', [
'public' => false,
'show_in_rest' => true,
'rest_controller_class' => Curate_Rest_Controller::class,
'capability_type' => 'post',
'rewrite' => false,
]);
}
}
Loading