admin管理员组

文章数量:1124388

The title of my WP about page contains apostrophes. When I fetch that page through REST API from my Vue.js frontend, the apostrophes in the title become ASCII characters.

How to avoid this?

(and why is the title also contained in some rendered sub-property?)

The /wp/v2/pages/?slug=about REST API route returns:

{
  ...,
  title {
    rendered: "Who’s this?"
  }
}

Instead of this ASCII mess, it should simply be: "Who's this?"

For the record, in my Vue.js frontend I'm fetching this REST API route thus:

axios
  .get('/wp/v2/pages/?slug=about')
  .then(response => {
    console.log(response.data[0])
  })
  .catch(error => {
    console.log(error)
  })

The title of my WP about page contains apostrophes. When I fetch that page through REST API from my Vue.js frontend, the apostrophes in the title become ASCII characters.

How to avoid this?

(and why is the title also contained in some rendered sub-property?)

The /wp/v2/pages/?slug=about REST API route returns:

{
  ...,
  title {
    rendered: "Who’s this?"
  }
}

Instead of this ASCII mess, it should simply be: "Who's this?"

For the record, in my Vue.js frontend I'm fetching this REST API route thus:

axios
  .get('/wp/v2/pages/?slug=about')
  .then(response => {
    console.log(response.data[0])
  })
  .catch(error => {
    console.log(error)
  })
Share Improve this question edited Mar 6, 2024 at 23:14 drake035 asked Mar 6, 2024 at 22:38 drake035drake035 1,2177 gold badges34 silver badges57 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Instead of this ASCII mess, it should simply be: "Who's this?"

No, it should not.

If you make a OPTIONS request to the /wp-json/wp/v2/pages path, you'll see the schema which defines all the fields that exist within a Page record, like so for the post title field, via JavaScript's fetch():

Therefore, title.rendered is meant for display and thus, filters like wptexturize() ( which converts the ' to ’s ) are applied to the raw post title.

  • See WP_REST_Posts_Controller::prepare_item_for_response() which uses get_the_title() which applies the filter hook the_title.

  • See also WP_REST_Posts_Controller::get_item_schema() which defines core post/page record's fields.

If you want to get the raw post title, you can use /wp/v2/pages?slug=about&context=edit, i.e. set the context parameter to edit, and read the raw title via title.raw, but authentication is required.

  • Alternate options (apart from disabling the texturize filters): filter the schema or modify the REST API response, or create a custom REST field which would return the raw title. But then, it is up to you to decide on the most appropriate option in your case. ✌

本文标签: Field fetched through REST API contains ASCII version of special characters