2

I am using Wordpress rest API with a React application. I have a category called 'Q&A', and wordpress templating system is able to translate it properly when rendering.

However, when using dynamic views with react and retrieving that data from Wordpress API, that name is returned as "name": "Q&A" . Also considering that I want to include categories as an initial state for React in the HTML delivered, I guess that encoding is correct.

I suppose that is client's responsibility to translate those fields. Which is the best way to translate those responses in actual strings to be rendered?

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
andersuamar
  • 193
  • 10
  • Possible duplicate of [Decode & back to & in JavaScript](https://stackoverflow.com/questions/3700326/decode-amp-back-to-in-javascript) – jmargolisvt Nov 09 '17 at 18:36

2 Answers2

1

This js function will parse those ampersands for you:

function parseAmp(s){
  return s.replace('&', '&');
}

Hope that helps!

Tanner Eustice
  • 164
  • 1
  • 9
0

Write this code in your function.php file or custom plugin:

function is_get_posts_request( \WP_REST_Request $request ) {
    return 'GET' === $request->get_method();
}

function mutate_get_posts_response( $response ) {
    if ( ! ( $response instanceof \WP_REST_Response ) ) {
        return;
    }
    $data = array_map(
        'prefix_post_response',
        
        $response->get_data()
    );
    $response->set_data( $data );
}

function prefix_post_response(  array $post ) {
    if ( isset( $post['title']['rendered'] ) ) {
      
        //$type = $request->get_param( 'type' ),
        $post['title']['rendered'] = html_entity_decode( $post['title']['rendered']);
    }
    return $post;
}

add_filter(
    'rest_request_after_callbacks',
    function( $response, array $handler, \WP_REST_Request $request ) {
        if ( is_get_posts_request( $request ) ) {
            mutate_get_posts_response( $response );
        }
        return $response;
    },
    10,
    3
);

The plugin link is here

Gass
  • 7,536
  • 3
  • 37
  • 41