2

I'm trying to get WordPress website title using javascript and WP API plugin

I didn't find any example on how to get the site's name but I found the variable name under the entities section in the developer guide

function _updateTitle(documentTitle) {
    document.querySelector('title').innerHTML = 
        documentTitle + ' | '+ $http.get('wp-json/name');
}

The output string of $http.get('wp-json/name') is [object Object]

Output

Does anyone know how to use fix this?

Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185
  • So it’s an object, that probably has the value you are looking for set as a property – so log it to console, and see what it actually contains. – CBroe Jul 05 '15 at 16:42

2 Answers2

3

You didn't get enough context. What's $http? What happens when you go to wp-json/name directly in your browser? Here's what I see:

[{
  "code":"json_no_route",
  "message":"No route was found matching the URL and request method"
}]

Here's a simple example to get you the title:

var siteName;
$.getJSON( "/wp-json", function( data ) {
  siteName = data.name;
});
Paul Schreiber
  • 12,531
  • 4
  • 41
  • 63
  • thank you, I got it working like so: `function _updateTitle(documentTitle, pageTitle) { $http.get('wp-json').success(function( data ) { document.querySelector('title').innerHTML = documentTitle + ' | ' + data.name; WPService.pageTitle = pageTitle; }); }` – Murhaf Sousli Jul 05 '15 at 19:46
1

See more elegant solution here https://wordpress.stackexchange.com/a/314767/94636 response will not contain extra data like: authentication: [] namespaces: ["oembed/1.0", "akismet/v1", "acf/v3", "wp/v2"] routes: {/: {namespace: "", methods: ["GET"],…},…} timezone_string: "" ... _links: {help: [{href: "http://v2.wp-api.org/"}]}

basil
  • 3,482
  • 2
  • 22
  • 20