How to Modify “title” in WP-JSON response but only

2019-01-20 19:53发布

问题:

In a WP site, is there a way to change/filter the "title" in the wp-json linked to within the header? For example, if on a wp-json page there is:

"title":"Listing Details"

Can this be changed to:

"title":"Some Other Title"

The reason for wanting to do this is that a software purchased generates pages from a database using one post as a template, presumably via some sort of htaccess rules. These pages are generated from a single WP page. Other attributes are manipulated, but not this. Thus, if the page title in WP Admin is "Details" but the page's title and H1 in the HTML, via this purchased software, is instead Rotten Egg Specifications," the title and H1 will populate with "Rotten Egg Specifications" but the title attribute in the json will still say "Details."

I would think there is a way to filter this within functions.php, but I can't find the relevant documentation. Another I've actually tried - which is my backup plan - is code to disable this for a specific post as follows:

function elim_json($content)
{
if ( is_single( '17' ) {
$content = str_replace('rel="alternate" type="text/xml+oembed"', 'rel="" 
type=""',$content);
return $content;
}
}
add_filter('wp_headers','elim_json');

Again, however, disabling the link from within the post is not the preferred method. I would rather change what is displayed by the page linked to within the header via HTML like the following:

<link rel="alternate" type="application/json+oembed" href="https://www.someurl.com/wp-json/oembed/1.0/embed?url=encoded_url_here" /> 

I think the answer is in the codex re actions and filters for the rest api: http://v2.wp-api.org/extending/hooks/

Here I tried adding the following in the functions.php file:

add_action( 'rest_api_init', 'change_wp_json_url' );
function change_wp_json_url() {
    register_rest_field( 'post',
        'starship',
        array(
            'get_callback'    => 'slug_get_starship',
            'update_callback' => 'slug_update_starship',
            'schema'          => null,
        )
    );
}

I'm not sure this is remotely close to correct.