{"id":1092,"date":"2022-05-18T14:27:50","date_gmt":"2022-05-18T14:27:50","guid":{"rendered":"https:\/\/mklasen.com\/?p=1092"},"modified":"2023-08-14T10:45:39","modified_gmt":"2023-08-14T10:45:39","slug":"using-the-wordpress-rest-api","status":"publish","type":"post","link":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/","title":{"rendered":"Using the WordPress REST API"},"content":{"rendered":"\n

The WordPress REST API has become the go-to for any communication between the front-end and back-end. We’ve come a long way, from using admin-ajax to a professional, flexible and extendible REST API.<\/p>\n\n\n\n

Registering routes<\/strong><\/p>\n\n\n\n

Registering a REST endpoint is pretty easy, below you’ll find some ready-to-use code, including the plugin headers. <\/p>\n\n\n\n

 'GET',\n        'callback' => function($request) {\n            return $request->get_params();\n        },\n        'permission_callback' => function () {\n            return current_user_can( 'manage_options' );\n        }\n    ));\t\n});<\/code><\/pre>\n\n\n\n

This is everything you need to register a new endpoint in the REST API. The example above returns the parameters that you send as an example, so you can experiment and see what data our REST endpoint is receiving.<\/p>\n\n\n\n

The front-end part<\/strong><\/p>\n\n\n\n

We can send data to this endpoint with a fetch or ajax call in javascript.<\/p>\n\n\n\n

Example with Fetch<\/strong><\/p>\n\n\n\n

fetch('https:\/\/example.com\/wp-json\/example\/v1\/action?param1=test¶m2=test2')\n  .then(response => response.json())\n  .then(data => console.log(data));<\/code><\/pre>\n\n\n\n

Example with jQuery ajax’s method.<\/p>\n\n\n\n

jQuery.ajax({\n    url: ''https:\/\/example.com\/wp-json\/example\/v1\/action?param1=test¶m2=test2',\n    method: 'GET'\n}, function(data, status){\n    console.log(data);\n});<\/code><\/pre>\n\n\n\n

This should show us an array containing param1 and param2 in the console.<\/p>\n\n\n\n

User authentication using the WordPress REST API<\/strong><\/p>\n\n\n\n

When it’s about user authentication, it’s handy to include the ‘wp-api’ dependency when enqueueing your script;<\/p>\n\n\n\n

wp_enqueue_script('your-script', 'path_to_your_script', array('wp-api'));<\/code><\/pre>\n\n\n\n

This gives access to the wpApiSettings variable in javascript, allowing you to access the user nonce:<\/p>\n\n\n\n

console.log(wpApiSettings.nonce);<\/code><\/pre>\n\n\n\n

This means we can send the nonce to our REST API endpoint and use that to authenticate the user.<\/p>\n\n\n\n

An example of communicating with the REST API with an authenticated user using the WP Nonce with fetch:<\/p>\n\n\n\n

fetch('https:\/\/example.com\/wp-json\/example\/v1\/action?param1=test¶m2=test2', {\n  method: 'GET',\n  headers: {\n    'X-WP-Nonce': wpApiSettings.nonce\n  }\n})\n  .then(response => response.json())\n  .then(data => console.log(data));<\/code><\/pre>\n\n\n\n

An example of communicating with the REST API with an authenticated user using the WP Nonce with jQuery ajax:<\/p>\n\n\n\n

jQuery.ajax({\n    url: 'https:\/\/example.com\/wp-json\/example\/v1\/action?param1=test¶m2=test2',\n    method: 'GET',\n    beforeSend: function (xhr) {\n        xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);\n    }\n}, function(data, status){\n    console.log(data);\n});<\/code><\/pre>\n\n\n\n

That’s it!<\/strong> You can basically go anywhere from here, ex: converting the GET requests to POST requests<\/strong>.<\/p>\n\n\n\n

More info on REST endpoints: https:\/\/developer.wordpress.org\/reference\/functions\/register_rest_route\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"

The WordPress REST API has become the go-to for any communication between the front-end and back-end. We’ve come a long way, from using admin-ajax to a professional, flexible and extendible REST API. Registering routes Registering a REST endpoint is pretty easy, below you’ll find some ready-to-use code, including the plugin headers. This is everything you […]<\/p>\n","protected":false},"author":1,"featured_media":1094,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"_genesis_hide_title":false,"_genesis_hide_breadcrumbs":false,"_genesis_hide_singular_image":false,"_genesis_hide_footer_widgets":false,"_genesis_custom_body_class":"","_genesis_custom_post_class":"","_genesis_layout":"","footnotes":""},"categories":[1],"tags":[],"acf":[],"yoast_head":"\nUsing the WordPress REST API - Marinus Klasen<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\" \/>\n<meta property=\"og:locale\" content=\"nl_NL\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Using the WordPress REST API - Marinus Klasen\" \/>\n<meta property=\"og:description\" content=\"The WordPress REST API has become the go-to for any communication between the front-end and back-end. We’ve come a long way, from using admin-ajax to a professional, flexible and extendible REST API. Registering routes Registering a REST endpoint is pretty easy, below you’ll find some ready-to-use code, including the plugin headers. This is everything you […]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\" \/>\n<meta property=\"og:site_name\" content=\"Marinus Klasen\" \/>\n<meta property=\"article:publisher\" content=\"http:\/\/facebook.com\/marinus.klasen\" \/>\n<meta property=\"article:author\" content=\"http:\/\/facebook.com\/marinus.klasen\" \/>\n<meta property=\"article:published_time\" content=\"2022-05-18T14:27:50+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-08-14T10:45:39+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1534\" \/>\n\t<meta property=\"og:image:height\" content=\"652\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Marinus Klasen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@http:\/\/twitter.com\/marinusklasen\" \/>\n<meta name=\"twitter:site\" content=\"@marinusklasen\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Marinus Klasen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minuten\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\"},\"author\":{\"name\":\"Marinus Klasen\",\"@id\":\"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29\"},\"headline\":\"Using the WordPress REST API\",\"datePublished\":\"2022-05-18T14:27:50+00:00\",\"dateModified\":\"2023-08-14T10:45:39+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\"},\"wordCount\":266,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29\"},\"image\":{\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png\",\"articleSection\":[\"General\"],\"inLanguage\":\"nl-NL\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\",\"url\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\",\"name\":\"Using the WordPress REST API - Marinus Klasen\",\"isPartOf\":{\"@id\":\"https:\/\/mklasen.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png\",\"datePublished\":\"2022-05-18T14:27:50+00:00\",\"dateModified\":\"2023-08-14T10:45:39+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#breadcrumb\"},\"inLanguage\":\"nl-NL\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"nl-NL\",\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage\",\"url\":\"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png\",\"contentUrl\":\"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png\",\"width\":1534,\"height\":652},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/mklasen.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"General\",\"item\":\"https:\/\/mklasen.com\/general\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Using the WordPress REST API\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/mklasen.com\/#website\",\"url\":\"https:\/\/mklasen.com\/\",\"name\":\"Marinus Klasen\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/mklasen.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"nl-NL\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29\",\"name\":\"Marinus Klasen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"nl-NL\",\"@id\":\"https:\/\/mklasen.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/mklasen.com\/content\/uploads\/2021\/01\/DONE1171.jpg\",\"contentUrl\":\"https:\/\/mklasen.com\/content\/uploads\/2021\/01\/DONE1171.jpg\",\"width\":1500,\"height\":1000,\"caption\":\"Marinus Klasen\"},\"logo\":{\"@id\":\"https:\/\/mklasen.com\/#\/schema\/person\/image\/\"},\"description\":\"Marinus has been working in software\/web development for more than a decade. Since 2020 his attention shifted on sharing knowledge and developing products and tools for sharing knowledge. Marinus Klasen on Twitter\",\"sameAs\":[\"http:\/\/facebook.com\/marinus.klasen\",\"https:\/\/nl.linkedin.com\/in\/marinusklasen\",\"https:\/\/twitter.com\/http:\/\/twitter.com\/marinusklasen\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Using the WordPress REST API - Marinus Klasen","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/","og_locale":"nl_NL","og_type":"article","og_title":"Using the WordPress REST API - Marinus Klasen","og_description":"The WordPress REST API has become the go-to for any communication between the front-end and back-end. We’ve come a long way, from using admin-ajax to a professional, flexible and extendible REST API. Registering routes Registering a REST endpoint is pretty easy, below you’ll find some ready-to-use code, including the plugin headers. This is everything you […]","og_url":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/","og_site_name":"Marinus Klasen","article_publisher":"http:\/\/facebook.com\/marinus.klasen","article_author":"http:\/\/facebook.com\/marinus.klasen","article_published_time":"2022-05-18T14:27:50+00:00","article_modified_time":"2023-08-14T10:45:39+00:00","og_image":[{"width":1534,"height":652,"url":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png","type":"image\/png"}],"author":"Marinus Klasen","twitter_card":"summary_large_image","twitter_creator":"@http:\/\/twitter.com\/marinusklasen","twitter_site":"@marinusklasen","twitter_misc":{"Written by":"Marinus Klasen","Est. reading time":"2 minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#article","isPartOf":{"@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/"},"author":{"name":"Marinus Klasen","@id":"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29"},"headline":"Using the WordPress REST API","datePublished":"2022-05-18T14:27:50+00:00","dateModified":"2023-08-14T10:45:39+00:00","mainEntityOfPage":{"@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/"},"wordCount":266,"commentCount":0,"publisher":{"@id":"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29"},"image":{"@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage"},"thumbnailUrl":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png","articleSection":["General"],"inLanguage":"nl-NL","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/","url":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/","name":"Using the WordPress REST API - Marinus Klasen","isPartOf":{"@id":"https:\/\/mklasen.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage"},"image":{"@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage"},"thumbnailUrl":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png","datePublished":"2022-05-18T14:27:50+00:00","dateModified":"2023-08-14T10:45:39+00:00","breadcrumb":{"@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#breadcrumb"},"inLanguage":"nl-NL","potentialAction":[{"@type":"ReadAction","target":["https:\/\/mklasen.com\/using-the-wordpress-rest-api\/"]}]},{"@type":"ImageObject","inLanguage":"nl-NL","@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#primaryimage","url":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png","contentUrl":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png","width":1534,"height":652},{"@type":"BreadcrumbList","@id":"https:\/\/mklasen.com\/using-the-wordpress-rest-api\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/mklasen.com\/"},{"@type":"ListItem","position":2,"name":"General","item":"https:\/\/mklasen.com\/general\/"},{"@type":"ListItem","position":3,"name":"Using the WordPress REST API"}]},{"@type":"WebSite","@id":"https:\/\/mklasen.com\/#website","url":"https:\/\/mklasen.com\/","name":"Marinus Klasen","description":"","publisher":{"@id":"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/mklasen.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"nl-NL"},{"@type":["Person","Organization"],"@id":"https:\/\/mklasen.com\/#\/schema\/person\/bbad02776afb72dfba2ebfe1956a4e29","name":"Marinus Klasen","image":{"@type":"ImageObject","inLanguage":"nl-NL","@id":"https:\/\/mklasen.com\/#\/schema\/person\/image\/","url":"https:\/\/mklasen.com\/content\/uploads\/2021\/01\/DONE1171.jpg","contentUrl":"https:\/\/mklasen.com\/content\/uploads\/2021\/01\/DONE1171.jpg","width":1500,"height":1000,"caption":"Marinus Klasen"},"logo":{"@id":"https:\/\/mklasen.com\/#\/schema\/person\/image\/"},"description":"Marinus has been working in software\/web development for more than a decade. Since 2020 his attention shifted on sharing knowledge and developing products and tools for sharing knowledge. Marinus Klasen on Twitter","sameAs":["http:\/\/facebook.com\/marinus.klasen","https:\/\/nl.linkedin.com\/in\/marinusklasen","https:\/\/twitter.com\/http:\/\/twitter.com\/marinusklasen"]}]}},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816.png","featured_image_src":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816-600x400.png","featured_image_src_square":"https:\/\/mklasen.com\/content\/uploads\/2022\/05\/Markup-on-2022-05-18-at-162816-600x600.png","author_info":{"display_name":"Marinus Klasen","author_link":"https:\/\/mklasen.com\/author\/mklasen\/"},"_links":{"self":[{"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/posts\/1092"}],"collection":[{"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/comments?post=1092"}],"version-history":[{"count":3,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/posts\/1092\/revisions"}],"predecessor-version":[{"id":1383,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/posts\/1092\/revisions\/1383"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/media\/1094"}],"wp:attachment":[{"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/media?parent=1092"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/categories?post=1092"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mklasen.com\/wp-json\/wp\/v2\/tags?post=1092"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}