Custom WordPress Post API

User
create custom post detail rest api wordpress

{
"id": 212408,
"date": "2024-12-19T06:00:09Z",
"modifiedDate": "2024-12-17T12:24:07Z",
"link": "https://connachttribune.ie/puma-gen-e-joins-brands-range-of-all-electric-vehicles/",
"title": "",
"content":"",
"excerpt": "",
"author": {
"id": "475",
"name": "Gerry Murphy"
},
"images": {
"thumbnail": "https://connachttribune.ie/wp-content/uploads/2024/12/FORD-PUMA-GEN-E-150×150.jpg",
"fullSize": "https://connachttribune.ie/wp-content/uploads/2024/12/FORD-PUMA-GEN-E.jpg",
"mediumSize": "https://connachttribune.ie/wp-content/uploads/2024/12/FORD-PUMA-GEN-E-300×216.jpg"
},
"categories": [
{
"id": 2977,
"name": "Connacht Tribune"
},
{
"id": 58823,
"name": "Motors"
}
]
}

Assistant
To create a custom post detail REST API endpoint in WordPress that returns the specified data structure, you can follow these steps:

### Steps to Implement:

1. **Register a REST Route**: Use `register_rest_route` in WordPress to define a custom REST API endpoint.

2. **Fetch Post Data**: Use WordPress functions such as `get_post`, `get_the_author_meta`, `get_the_post_thumbnail_url`, and taxonomy functions to fetch the required data.

3. **Format the Data**: Structure the data in the desired JSON format.

4. **Return the Response**: Return the formatted response as JSON.

### Code Implementation:
Add the following code to your theme's `functions.php` file or a custom plugin:

function custom_post_detail_api( $data ) {
    $post_id = $data['id'];

    // Fetch the post
    $post = get_post( $post_id );
    if ( ! $post || $post->post_status !== 'publish' ) {
        return new WP_Error( 'post_not_found', 'Post not found', array( 'status' => 404 ) );
    }

    // Get author details
    $author_id = $post->post_author;
    $author_name = get_the_author_meta( 'display_name', $author_id );

    // Get post thumbnails
    $thumbnail = get_the_post_thumbnail_url( $post_id, 'thumbnail' );
    $full_size = get_the_post_thumbnail_url( $post_id, 'full' );
    $medium_size = get_the_post_thumbnail_url( $post_id, 'medium' );

    // Get categories
    $categories = get_the_terms( $post_id, 'category' );
    $categories_data = array();

    if ( $categories && ! is_wp_error( $categories ) ) {
        foreach ( $categories as $category ) {
            $categories_data[] = array(
                'id'   => $category->term_id,
                'name' => $category->name,
            );
        }
    }

    // Prepare response data
    $response_data = array(
        'id'           => $post->ID,
        'date'         => get_the_date( 'c', $post ),
        'modifiedDate' => get_the_modified_date( 'c', $post ),
        'link'         => get_permalink( $post ),
        'title'        => get_the_title( $post ),
        'content'      => apply_filters( 'the_content', $post->post_content ),
        'excerpt'      => get_the_excerpt( $post ),
        'author'       => array(
            'id'   => $author_id,
            'name' => $author_name,
        ),
        'images'       => array(
            'thumbnail'   => $thumbnail,
            'fullSize'    => $full_size,
            'mediumSize'  => $medium_size,
        ),
        'categories'   => $categories_data,
    );

    return rest_ensure_response( $response_data );
}

function register_custom_post_detail_route() {
    register_rest_route(
        'custom-api/v1',
        '/post-detail/(?P<id>d+)',
        array(
            'methods'  => 'GET',
            'callback' => 'custom_post_detail_api',
        )
    );
}
add_action( 'rest_api_init', 'register_custom_post_detail_route' );

### Explanation:
1. **Route Registration**:
– Registers the endpoint `/wp-json/custom-api/v1/post-detail/{id}`.
– `{id}` is a placeholder for the post ID.

2. **Data Fetching**:
– Fetches post details, author info, and category terms.
– Uses `get_the_post_thumbnail_url` for image URLs.

3. **Response Formatting**:
– Structures the response data to match your required format.

4. **Error Handling**:
– Returns a `404` error if the post is not found or not published.

### Test the API:
After adding the code, test your endpoint by visiting:

https://yourdomain.com/wp-json/custom-api/v1/post-detail/{id}

Replace `{id}` with a valid post ID.

Leave a Comment

Your email address will not be published. Required fields are marked *