For many reasons you might want to exclude certain fields from WP API response in certain circumstances. In this short post I’ll be showing you how to remove the “content” field from WP API response when visiting
Say for performances’ sake we really don’t want the whole post content to show when we listing posts, since we usually just need excerpt in such case. The code snippet is very straightforward as below:
The trick lies in we check the
$request parameter to tell if this is a request to list posts (at line 5-8). Many of us WP developers may feel frustrated about we can’t use these handy
is_*() functions such as
is_archive() when we hack around WP API.
The closest thing we can do is by checking the
$request and tell from the parameters it gets. In this case we check if the “
id” parameter exists, and if it does, we can confidently say it’s a single post API call instead of a listing posts call. Not sure about this? You can check source code in WP core to see that’s how
Now you get the idea what “last but not least” is all about, right? 😉 Next time be sure to check every parameter for a hook so you can really make use of it.
Still here’s a friendly note from the WP API team that changing API response is discouraged so please do so only when you understand the consequences.
If you’re trying to hack around WP API but having no idea on how to do it, just leave a comment or send me a tweet (@1fixdotio), I’ll get back to you as soon as I can. Talk soon!