Display post title from WordPress excluding a string via API

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.

tech