Imagine you have custom post types - Users. There are fields for each user as the post title, description, image, and rules. All titles are names of the Users and all they have Mr. before the names. What is the correct way and how to display all these fields via API in another site(not WordPress) but for the titles to exclude/strip the string Mr.?
1 Answer
If you're pulling REST API data from a WordPress site ("server") to a non-WordPress site ("client"), your client site won't have access to WordPress functions like get_the_title()
, etc.
What you will receive from the server is a JSON string that will look something like this:
// eg. from example.com/wp-json/wp/v2/posts
[
{
"id":10887,
"date":"2022-05-04T11:25:43",
"date_gmt":"2022-05-04T16:25:43",
"guid":
{
"rendered":"https:\/\/example.com\/?p=10887"
},
"modified":"2022-05-04T15:43:25",
"modified_gmt":"2022-05-04T20:43:25",
"slug":"bacon-its-whats-for-dinner",
"status":"publish",
"type":"post",
"link":"https:\/\/example.com\/2022\/05\/04\/bacon-its-whats-for-dinner\/",
"title":
{
"rendered":"Bacon: It’s What’s for Dinner"
},
"content":
{
"rendered":"{some content here}",
"protected":false
},
"author":7,
"featured_media":0,
# ... more and more ...
},
{ ... }
]
If you're using PHP, you can convert that JSON string to an array of stdClass
objects using json_decode()
.
Assuming that $json
is the JSON response you've received from your WordPress server's REST API, and that you're using the standard WP posts
endpoint, you can do something like this:
$data = json_decode( $json );
foreach ( $data as $post ) {
$title = $post->title->rendered;
$my_title = str_replace( 'Mr.', '', $title );
}
If you've got some other custom endpoint set up for your custom posts, you'll need to use the appropriate property in your JSON data to get the title (and any other data you might need to display/store/retrieve on the client side).
If you haven't encountered it, I recommend looking through the REST API Handbook that WordPress provides.
-
Thanks for your explanation.l I think I got how to do the things to work. Currently the line of code that pulL/display the data for the title looks similar to: $users->'title' = $post->post_title; But that pull/display the whole title how you know. So using your explanation and code example I think I will do the things to work how I want. Thanks May 7, 2022 at 15:54
str_replace()
to strip theMr.
from the titles; if you're not using PHP, you'll need to find out how to do string replacements in your language of choice. (It should be there, it's a core feature of programming languages generally.)