WP/PHP getting API data and using hook Below are the two things I'm trying to solve, logically. This is just a proof of concept; and I'm not implementing this on real data nor via full plugin at this time. Just looking at logic and syntax solutions. 

Below are the (2) requirements.

1.) Given an API route for retrieving a specific record, do the following:


Get the id param
Return a 404 if the record isn't found
Return a response with the record if it is found


Route format:

/publishers/(?P&lt;id&gt;\d+)

/publishers/397


2.) Add a WordPress hook to determine the value of the visible property on some item. Then use that hook elsewhere to change the value to false;

Below is what I have so far. Which appears correct; but just would like to see if there is a more optimal way, and/or this is still best approach. Just some feedback on my code solution; via the above two points.

My Code solutions:



&lt;?php
function get_publisher( \WP_REST_Request $request ) {   
    $request = json_decode( $request );
    $publisher_id = $request[ 'ID' ];
    if ( empty( $publisher ) ) {

        $response = [
            'status'    =&gt; 404,
            'data'      =&gt; [
                'errors' =&gt; [
                        'general' =&gt; 'Sorry, no record was found.'
                ],
            ],
        ];
        return json_encode( $response );
    }
    $response = [
        'status'    =&gt; 200,
        'data'      =&gt; [
            'publisher' =&gt; $publisher,
        ]
    ];
    return json_encode( $response );
}
function modify_item( $item ) {
    $item-&gt;visible = apply_filters( 'item_visibility', true ); 

    return $item;
}
function hide_item() {
    return false;
}
add_filter( 'item_visibility', 'hide_item' );
You will need to settle on the variable name containing $request[ 'ID' ];. At the moment, you are using $publisher_id and $publisher ...which of course is a script fouling typo. I'd probably avoid declaring the variable, because I don't find a declarative coding style to be very beneficial in this case.
You could use a different syntax to declare your array to be less verbose. For example:

 $response['status'] = 404;
 $response['data']['errors']['general'] = 'Sorry, no record was found.';

By writing an if-else, you can avoid rewriting json_encode().


..I don't WP so I cannot say if there any native techniques to leverage.

The first function could look like this:

function get_publisher(\WP_REST_Request $request) {   
    $request = json_decode($request);
    if (empty($request['ID'])) {
        $response['status'] = 404;
        $response['data']['errors']['general'] = 'Sorry, no record was found.';
    } else {
        $response['status'] = 200;
        $response['data']['publisher'] = $request['ID'];
    }
    return json_encode($response);
}