WordPress cors error

Learn how to fix CORS errors in WordPress to successfully load JavaScript and AJAX requests from any third-party server on your site.

WordPress sites will work perfectly fine as long as you use it in a simple manner. It will throw you different types of errors, the moment you want to add additional features and third-party scripts. In our earlier article, we have explained about the problem with WP-Cron while using Cloudflare. Similarly, CORS error is another popular WordPress error that many users struggle to fix. In this article, we will explore what is CORS and how to fix CORS errors in WordPress.

What is CORS?

CORS stands for Cross-Origin Resource Sharing. By default, a web browser allows all the requests originated from the same server using same-origin security policy. Here is a precise definition of  same-origin policy from Wikipedia:

Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.

Wikipedia

Now that you can easily understand the purpose of cross-origin. It allows you to successfully load the scripts and other resources from another domain or server. Below is a beautiful image from MDN explaining the concept of same-origin and cross-origin requests.

CORS MDN

Example of CORS and Seeing Errors

Let’s take a case that you are opening a page https://site1.com/page1 which has an embedded JavaScript and calls it from https://site2.com/page2. CORS will tell the browser whether the cross-origin request from site2 is allowed by site 1. Otherwise, browser will block this request and show CORS related errors in the console.

The best example of CORS is using advertisement scripts from third-party domains on your site. Browsers like Chrome, Firefox, Safari and Edge will block the ad scripts if you are not allowing CORS on your server. When you see an advertisement or any other output is not loading on the page, right click on the page and select “Inspect” option. This will open the browser’s developer console and go to “Console” section.

You will see different types of error showing 403, 401 status codes or errors without status code. For example, below is the console errors showing in Google Chrome and the error states clearly “Access to XMLHttpRequest at ‘……’ from origin ‘…..’ has been blocked by CORS policy”. You can also see the reason next to the error stating that “The ‘Access-Control-Allow-Origin’ header has a value ‘…..’ that is not equal to the supplied origin.”

CORS Error in Google Chrome
CORS Error in Google Chrome

The same page when opened in Mac Safari browser will show different errors like below. It shows the error as “Origin ‘….’ is not allowed by Access-Control-Allow-Origin. Status code: 401”. You can also see errors like “XMLHttpRequest cannot load ‘…..’ due to access control checks”.

CORS Error in Safari Browser
CORS Error in Safari Browser

Whenever you see console errors related to access control checks, you can safely assume they are related to CORS issue. As a result, you the script will fail to load and you will not see the advertisement or the expected result on the page.

Now that you understand what is CORS and how to find the related errors in browser console. The next step is to fix the error so that your page loads on browsers without any errors. In simple, you have to add the following code in your .htaccess file to allow cross-origin resource sharing on your server.

Access-Control-Allow-Origin: *

There are three different ways you can achieve this depending upon the scenario.

1. Allowing All Sites

This is the most common way of allowing CORS. If you want to allow any third-party server requests on your site, then add the following code in your htaccess file. The * is used as a wildcard for allowing any third-party domains.

<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: *
</ifModule>

2. Allow Specific Domain

The above method is not recommended as any hijackers can inject malicious script files on your site and cause trouble. The correct approach is to allow cross-origin resource sharing only from the domain you need. You can replace the * with the name of the domain as given below:

<ifModule mod_headers.c>
Header set Access-Control-Allow-Origin: https://site2.com
</ifModule>

Unfortunately, this is not easy to do as you need server side coding to validate the domain allowed in the header access control. Therefore, option #1 is used by many WordPress users as it does not need any additional coding.

3. Allow Specific Files from All Servers

The last option is to restrict the file type you want to allow from third-party servers. For this, you can use the following code indicating the allowed file types in your htaccess file.

<IfModule mod_headers.c>
  <FilesMatch ".(png|css|js)$">
    Header set Access-Control-Allow-Origin: *
  </FilesMatch>
</IfModule>

This code will allow PNG images, CSS and JS files from any servers. You can add fonts and other image file types to allow them in CORS.

Other Considerations

There are few additional considerations you may need to aware when allowing cross-origin resource sharing in WordPress.

  • Some hosting companies needs you to disable their caching for CORS to work. For example, if you are on SiteGround, you need to disable NGINX direct delivery under “Site Tools > Speed > Cache” section.
  • When using Cloudflare or any other CDN with caching setup, you may need to purge the cache completely for the changes to reflect from the origin server.
  • CORS can also create problem when using HTTP and HTTPS protocols. This will generally show as mixed content error in browser console and you need to force using HTTPS on your site to block other protocols.
  • Another consideration is serving static and other resources from subdomain to primary domain. This will work perfectly since both subdomain and primary domains are generally on the same origin server. However, it may also create problems depending upon the setup on your server. You can resolve this problem by specifically mentioning the subdomain as explained above in option #2.

I have this wordpress site with a plugin called JSON API. This plugin provides a JSON format for the content that is in the wordpress. I was able to enable CORS on the wordpress by adding header(«Access-Control-Allow-Origin: *»); on the php header. But when I tried the url that the JSON API plugin provides the CORS does not work anymore.

This is the wordpress site were I’m doing the tests… I used the test cors website to check if it was working and it is…
http://kiwa-app.loading.net/

But when I try with the url that the JSON api provides me, is not working anymore. I’m still have the error No ‘Access-Control-Allow-Origin’
http://kiwa-app.loading.net/?json=info

I will apreciate some help thanks!!!

asked Sep 6, 2014 at 16:01

Mario Sanchez Maselli's user avatar

I’ve used a few different WordPress API’s — but for those of you using the ‘official’ WP-API, I had much trouble with this CORS — and what I found was that between the .htaccess approach and a few others I stumbled upon… adding this to your theme functions.php worked best.

function add_cors_http_header(){
    header("Access-Control-Allow-Origin: *");
}
add_action('init','add_cors_http_header');

Be sure not to use any combinations of these ( .htaccess, header.php, api.php, functions.php ) as it will be angry at you.

answered Mar 22, 2015 at 23:24

sheriffderek's user avatar

sheriffdereksheriffderek

8,7006 gold badges40 silver badges69 bronze badges

9

Ok I finally figured out an easy way…

You just have to add:

     <? header("Access-Control-Allow-Origin: *"); ?>

On the file api.php, this file is located in wp-content/plugins/json-api/singletons/api.php

I hope it helps more people with the same problem!

answered Sep 8, 2014 at 7:26

Mario Sanchez Maselli's user avatar

7

Using WordPress 5.2.3 — whilst using GET and POST externally, the following finally opened sesame for me. I tried all of the answers above (to no avail) before finding this solution that worked for my case.

add_action( 'rest_api_init', function () {
    add_action( 'rest_pre_serve_request', function () {
        header( 'Access-Control-Allow-Headers: Authorization, Content-Type, X-WP-Wpml-Language', true );
        header("Access-Control-Allow-Origin: *");
    } );
}, 15 );

Hopefully WordPress will have an official doggy door-flap for CORS control in the future.

answered Sep 16, 2019 at 6:42

Grant's user avatar

2

Before the response is sent to the browser, we can run two action hooks and insert a new header():

do_action("json_api", $controller, $method);
do_action("json_api-{$controller}-$method");

The first one runs on every method, and the second one is to target specific methods. Here’s an implementation of the first one, with a commented way to find the second:

add_action( 'json_api', function( $controller, $method )
{
    # DEBUG
    // wp_die( "To target only this method use <pre><code>add_action('$controller-$method', function(){ /*YOUR-STUFF*/ });</code></pre>" );

    header( "Access-Control-Allow-Origin: *" );
}, 10, 2 );

answered Sep 7, 2014 at 13:04

brasofilo's user avatar

brasofilobrasofilo

25.2k15 gold badges90 silver badges178 bronze badges

1

Now that REST API is merged with core, we can use the rest_api_init action.

add_action( 'rest_api_init', function()
{
    header( "Access-Control-Allow-Origin: *" );
} );

answered Mar 26, 2019 at 16:35

Sudar's user avatar

SudarSudar

18.4k29 gold badges85 silver badges128 bronze badges

2

WordPress 5 (4.4+ actually) can handle it via WP Headers:

Try this:

add_filter( 'wp_headers', 'send_cors_headers', 11, 1 );
function send_cors_headers( $headers ) {
    $headers['Access-Control-Allow-Origin'] = $_SERVER[ 'HTTP_ORIGIN' ];
    return $headers;
}

Note that this will allow access from ANY source. For security you should try to do something like set an array of allowed domains that can make the request to your WordPress site and short-circuit the allow CORS if the domain making the request is not in the allowed list:

add_filter( 'wp_headers', 'send_cors_headers', 11, 1 );
function send_cors_headers( $headers ) {
    $allowed_domains = array( 'https://my.okdomain.com' , 'http://anothergoodone.com');
    if ( ! in_array( $_SERVER[ 'HTTP_ORIGIN' ] , $allowed_domains ) ) return $headers;
    $headers['Access-Control-Allow-Origin'] = $_SERVER[ 'HTTP_ORIGIN' ];
    return $headers;
}

answered Apr 4, 2019 at 16:31

Lance Cleveland's user avatar

Lance ClevelandLance Cleveland

3,0781 gold badge32 silver badges35 bronze badges

3

In wordpress goto plugins > JSON API > Edit

From the right hand file selection select

json-api/singletons/api.php

You will need to add the following line

header(«Access-Control-Allow-Origin: *»);

Your code should look similar to this once done. Adding this line anywhere else might not work as expected.

<?php
header("Access-Control-Allow-Origin: *"); 
class JSON_API {

  function __construct() {
    $this->query = new JSON_API_Query();
    $this->introspector = new JSON_API_Introspector();
    $this->response = new JSON_API_Response();
    add_action('template_redirect', array(&$this, 'template_redirect'));
    add_action('admin_menu', array(&$this, 'admin_menu'));
    add_action('update_option_json_api_base', array(&$this, 'flush_rewrite_rules'));
    add_action('pre_update_option_json_api_controllers', array(&$this, 'update_controllers'));
  }

  function template_redirect() {

answered Feb 18, 2016 at 11:38

Basil Abbas's user avatar

Basil AbbasBasil Abbas

1,7921 gold badge10 silver badges9 bronze badges

1

For anyone who is having this issue with multiple origins

In your server hosting your wordpress site, navigate to ../wp-content/plugins/json-rest-api and from here open the plugin.php file.

In this function

function json_send_cors_headers( $value ) {..}

Change the header

header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );

To

header( 'Access-Control-Allow-Origin: *' );

Hope this helps anyone who was incurring the same issues as I.

answered Mar 3, 2016 at 19:52

njsokol's user avatar

njsokolnjsokol

1193 silver badges11 bronze badges

The solution works with WordPress 5.1.1 and Gutenberg

add_filter('rest_url', function($url) {
    $url = str_replace(home_url(), site_url(), $url);
    return $url;
});

answered Apr 8, 2019 at 22:37

Shahbaz Ahmed's user avatar

1

In WordPress project go to following file and do like this:

In wp-includes/rest-api.php change:

header( 'Access-Control-Allow-Origin: ' . $origin );

to:

header( 'Access-Control-Allow-Origin: *' );

In wp-includes/http.php change:

header( 'Access-Control-Allow-Origin: ' . $origin );

to:

header( 'Access-Control-Allow-Origin: *' );

cabrerahector's user avatar

answered Feb 24, 2019 at 15:52

gui xiao's user avatar

2

On Crunchify Business site we have enabled HTTPS from day one. Recently WordPress.com announced 100% HTTPS enablement even for hosted domains at WordPress.com and that’s a great news.

While setting up HTTPS on WordPress site, we found a strange issue by looking at Chrome console output. Take a look at below screenshot.

Error: No Access-Control-Allow-Origin header is present on the requested resource.

How to fix Access Control Allow Origin issue for your HTTPS enabled WordPress site

First of all I’ve never seen this before for any WordPress site.

Of course, this is not a new term for us as we do have a detailed tutorial on CORS origin for Java: https://crunchify.com/what-is-cross-origin-resource-sharing-cors-how-to-add-it-to-your-java-jersey-web-server/

Using web.config and Java setting combination you could fix CORS origin issue easily.

Let’s understand what is Cross-origin resource sharing (CORS)?

CORS is industry standard for accessing web resources on different domains. It is very important security concept implemented by web browsers to prevent Javascript or CSS code from making requests against a different origin.

Let’s consider this scenario:

  • You have link from Domain1 which is opened in browser and asking for a JavaScript file from Domain2.
  • Now your web browser makes call to Domain2.
  • If on Domain2, you have a policy to accept request like JavaScript or CSS from only Domain2 and ignore all requests from other domains, then your browser’s Domain1 request will fail with an error.

In simple statement: If request is not coming from same domain or origin, just simply ignore it.

This is very important features which prevents hacking and resource stealing without owners’s knowledge.

Take a look at this below screenshot with error:

Mixed Content: The page was not loaded over HTTPS. This request has been blocked.

Mixed Content CORS origin error for Crunchify.com site

Why problem appeared on Crunchify.com site?

After investigation I came to know that I’ve setup http as my origin URL in MaxCDN setup admin console. It should be https.

Busiess.Crunchify.com and MAXCDN Origin URL issue

How did I fix this error?

Just changed Origin URL from http to https and issue resolved in my case. There is another way to fix an issue too.

Are you using Webfonts from Google, Typekit, etc?

There are multiple ways you could use Webfonts like @font-face or CSS3 methods, some browsers like Firefox & IE may refuse to embed the font when it’s coming from some non-standard 3rd party URL (like your blog) for same security reason.

In order to fix an issue for your WordPress blog, just put below into your .htaccess file.

<IfModule mod_headers.c>
  <FilesMatch ".(ttf|ttc|otf|eot|woff|woff2|font.css|css|js)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>

As you see Access-Control-Allow-Origin "*" allows you to access all resources and webfonts from all domains.

We got excellent question from Andreas on adding Access-Control-Allow-Origin on Subdomains

Access-Control-Allow-Origin on Subdomains

Just add below lines to .htaccess file and we should be good.

<ifmodule mod_headers.c="">
   SetEnvIf Origin "^(.*.domain.com)$" ORIGIN_SUB_DOMAIN=$1
   Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
   Header set Access-Control-Allow-Methods: "*"
   Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</ifmodule>

Hope this helps you the way you want.


Join the Discussion

If you liked this article, then please share it on social media. Still have any questions about an article, leave us a comment.

Share:

I’m an Engineer by profession, Blogger by passion & Founder of Crunchify, LLC, the largest free blogging & technical resource site for beginners. Love SEO, SaaS, #webperf, WordPress, Java. With over 16 millions+ pageviews/month, Crunchify has changed the life of over thousands of individual around the globe teaching Java & Web Tech for FREE.

Reader Interactions

Сайты WordPress будут работать отлично, если вы используете их простым способом. Он будет выдавать вам различные типы ошибок в тот момент, когда вы захотите добавить дополнительные функции и сторонние скрипты. В нашей предыдущей статье мы объяснили проблему с WP-Cron при использовании Cloudflare. Точно так же ошибка CORS — еще одна популярная ошибка WordPress, которую многие пользователи пытаются исправить. В этой статье мы рассмотрим, что такое CORS и как исправить ошибки CORS в WordPress.

Что такое КОРС?

CORS расшифровывается как Cross-Origin Resource Sharing. По умолчанию веб-браузер разрешает все запросы, исходящие с одного и того же сервера, с использованием политики безопасности одного источника. Вот точное определение политики того же происхождения из Википедии:

В соответствии с этой политикой веб-браузер разрешает сценариям, содержащимся на первой веб-странице, доступ к данным на второй веб-странице, но только в том случае, если обе веб-страницы имеют одинаковое происхождение.

Википедия

Теперь вы можете легко понять цель перекрестного происхождения. Он позволяет успешно загружать скрипты и другие ресурсы с другого домена или сервера. Ниже красивое изображение из МДН объясняя концепцию запросов из одного и того же источника и запросов из разных источников.

КОРС МДН

Пример CORS и просмотра ошибок

Предположим, вы открываете страницу https://site1.com/page1 со встроенным JavaScript и вызываете ее с https://site2.com/page2. CORS сообщит браузеру, разрешен ли запрос перекрестного происхождения с сайта 2 сайтом 1. В противном случае браузер заблокирует этот запрос и отобразит ошибки, связанные с CORS, в консоли.

Лучший пример CORS — использование рекламных скриптов со сторонних доменов на вашем сайте. Такие браузеры, как Chrome, Firefox, Safari и Edge, будут блокировать рекламные сценарии, если вы не разрешаете CORS на своем сервере. Когда вы видите, что реклама или любой другой вывод не загружается на странице, щелкните правой кнопкой мыши страницу и выберите опцию «Проверить». Это откроет консоль разработчика браузера и перейдет в раздел «Консоль».

Вы увидите различные типы ошибок с кодами состояния 403, 401 или ошибки без кода состояния. Например, ниже показаны ошибки консоли, отображаемые в Google Chrome, и в ошибке четко указано: «Доступ к XMLHttpRequest в ‘……’ из источника ‘…..’ заблокирован политикой CORS». Вы также можете увидеть причину рядом с ошибкой, указывающей, что «заголовок« Access-Control-Allow-Origin »имеет значение« … .. », которое не равно предоставленному источнику».

Ошибка CORS в Google ChromeОшибка CORS в Google Chrome

Та же страница при открытии в браузере Mac Safari будет отображать разные ошибки, как показано ниже. Он показывает ошибку как «Происхождение ‘….’ не разрешено Access-Control-Allow-Origin. Код состояния: 401». Вы также можете увидеть такие ошибки, как «XMLHttpRequest не может загрузить «…..» из-за проверок управления доступом».

Ошибка CORS в браузере SafariОшибка CORS в браузере Safari

Всякий раз, когда вы видите ошибки консоли, связанные с проверками контроля доступа, вы можете с уверенностью предположить, что они связаны с проблемой CORS. В результате у вас скрипт не загрузится и вы не увидите рекламу или ожидаемый результат на странице.

Теперь, когда вы понимаете, что такое CORS и как найти связанные ошибки в консоли браузера. Следующий шаг — исправить ошибку, чтобы ваша страница загружалась в браузерах без ошибок. Проще говоря, вы должны добавить следующий код в свой файл .htaccess, чтобы разрешить совместное использование ресурсов из разных источников на вашем сервере.

Доступ-Контроль-Разрешить-Происхождение: *

Есть три разных способа добиться этого в зависимости от сценария.

1. Разрешение всех сайтов

Это наиболее распространенный способ разрешения CORS. Если вы хотите разрешить любые сторонние серверные запросы на своем сайте, добавьте следующий код в файл htaccess. * используется в качестве подстановочного знака для разрешения любых сторонних доменов.

Набор заголовков Access-Control-Allow-Origin: *

2. Разрешить определенный домен

Вышеупомянутый метод не рекомендуется, так как любые угонщики могут внедрить вредоносные файлы сценариев на ваш сайт и вызвать проблемы. Правильный подход — разрешить обмен ресурсами между источниками только из нужного вам домена. Вы можете заменить * на имя домена, как указано ниже:

Набор заголовков Access-Control-Allow-Origin: https://site2.com

К сожалению, это непросто сделать, так как вам нужно кодирование на стороне сервера для проверки домена, разрешенного в управлении доступом к заголовку. Поэтому вариант № 1 используется многими пользователями WordPress, поскольку он не требует дополнительного кодирования.

3. Разрешить определенные файлы со всех серверов

Последний вариант — ограничить тип файла, который вы хотите разрешить со сторонних серверов. Для этого вы можете использовать следующий код, указывающий разрешенные типы файлов в вашем файле htaccess.

Набор заголовков Access-Control-Allow-Origin: *

Этот код позволит изображениям PNG, файлам CSS и JS с любых серверов. Вы можете добавить шрифты и другие типы файлов изображений, чтобы разрешить их использование в CORS.

Другие соображения

Есть несколько дополнительных соображений, которые вам, возможно, придется учитывать при разрешении общего доступа к ресурсам из разных источников в WordPress.

  • Некоторым хостинговым компаниям нужно, чтобы вы отключили кэширование для работы CORS. Например, если вы находитесь на SiteGround, вам необходимо отключить прямую доставку NGINX в разделе «Инструменты сайта > Скорость > Кэш».
  • При использовании Cloudflare или любого другого CDN с настройкой кэширования вам может потребоваться полностью очистить кеш, чтобы изменения отражались с исходного сервера.
  • CORS также может создавать проблемы при использовании протоколов HTTP и HTTPS. Обычно это отображается как ошибка смешанного содержимого в консоли браузера, и вам необходимо принудительно использовать HTTPS на вашем сайте, чтобы заблокировать другие протоколы.
  • Еще одним соображением является обслуживание статических и других ресурсов из поддомена в основной домен. Это будет работать отлично, поскольку и поддомен, и основной домен обычно находятся на одном и том же исходном сервере. Однако это также может создать проблемы в зависимости от настроек вашего сервера. Вы можете решить эту проблему, специально указав субдомен, как описано выше в варианте № 2.

Viewing 8 replies — 1 through 8 (of 8 total)

  • Hello there, @zackai! Thank you for reaching out with your topic.

    The new video optimization feature in version 1.6.0 of the plugin requires a feature called cross-origin isolation. For this to work, external resources being loaded from a different host need to provide an Access-Control-Allow-Origin header.

    If your site loads JavaScript files from a different subdomain, then your CDN needs to provide this Access-Control-Allow-Origin response header for all these assets. Access-Control-Allow-Origin: https://www.yourdomain.com or the less restrictive Access-Control-Allow-Origin: * should work.

    Please contact your website administrator or hosting provider to further assistance with setting the header.

    As a short-term workaround, you can disable video optimization in the Web Stories settings, which will also disable the cross-origin isolation and the need for these headers.

    Thanks.

    Thread Starter
    zackai

    (@zackai)

    Thanks, Luckyna.

    About setting the header, my original understanding is that it’s caused by that WebStories plugin is trying to load resources from the google server, and hence the cross-origin. But you are saying it’s because my hosting is trying to load javascript from another subdomain? Do I understand it correctly? If so, I will talk to my provider.

    As for disabling video optimization, it helps to mitigate the issues. Thanks.

    • This reply was modified 1 year, 9 months ago by zackai.

    Hi @zackai!

    But you are saying it’s because my hosting is trying to load javascript from another subdomain? Do I understand it correctly? If so, I will talk to my provider.

    Yep, that’s correct. This CORS error occurs when your site is trying to load files from a different domain than your WordPress domain, so your provider will need to help you adjust your CORS settings to make them less restrictive and allow these files to be accessed.

    Hope this helps! Let us know if you have any other questions.

    @zackai We will mark this as resolved, but please feel free to open a new support topic if you have any questions. Thanks again for your post!

    @luckynasan can you explain this a little more? If I have a WordPress website and a Google Cloud Storage bucket that acts as the CDN for all of the images, and these images don’t show up in Web Stories because of the CORS issue, do I need to make a fix in the htaccess file of the WordPress website or a fix in the Google Cloud Storage bucket?

    You’ll need to set up CORS on the Google Cloud Storage bucket. Follow the documentation at https://cloud.google.com/storage/docs/cross-origin to learn more about CORS and how to set it up on your bucket.

    hi, I saw an error like this:”Access to font at ‘https://mydomainname.com/wp-content/plugins/elementor/assets/lib/font-awesome/webfonts/fa-solid-900.woff2’ from origin ‘http://mydomainname.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. ”
    What should I do please?
    Need plug in or coding please?

    Thanks.

    • This reply was modified 1 year, 2 months ago by anniechoy. Reason: do not want to public my domain name

    @anniechoy If you’d like to open a new support topic we’d be happy to assist with your case individually. Thank you!

  • Viewing 8 replies — 1 through 8 (of 8 total)

    Cross-Origin Resource Sharing (CORS) is a relatively new problem in JavaScript development. Maybe I’m showing my age here, but I can distinctly remember when there were no concerns with loading JavaScript from all over the internet into your blog. It was new! It was fun! But as more and more of us got online, and JavaScript webpages turned into JavaScript applications, it became a huge security risk. Thus, we have our modern world where a JavaScript file can only be loaded outside of its domain if it contains the correct Access-Control-Allow-Origin headers.

    So, what do you do when you’re happily making a block (as part of your agency’s Gutenberg-first initiative, of course), and the API you are trying to access doesn’t have the correct headers? Let me show you a quick way to resolve a CORS error with the WordPress REST API. In particular, we’re going to create a custom REST endpoint and proxy our request through the WordPress API.

    I ran into this problem when revisiting my old custom oEmbed provider. I wanted to accomplish the same thing, but in JavaScript:

    Screenshot of code using fetch to call a backend.deviantart.com URL

    However, when trying to load the API from my local machine, I got these errors:

    Access Control Allow Origin errors in the JavaScript console

    In short, because the remote server backend.deviantart.com is not set up to allow an arbitrary web page to load its JavaScript, I could not call the API directly from my block using fetch. To get around this, we’ll be using the PHP backend and wp_remote_get.

    New REST Endpoint

    First, we need to set up our custom endpoint. This will allow us to call the WordPress backend from our block:

    You can read more about register_rest_route in the WordPress docs. With this code, we are setting up the following flow:

    1. Block will call /wp-json/oddevan/v1/devArtProxy/
    2. WordPress will call the proxy_deviantart_oembed_security function to find out if the current user has permissions to access this endpoint
    3. WordPress will call the proxy_deviantart_oembed function.

    Next, let’s check our security function:

    As you can see, it’s not very complicated. We just need to pass along whether the current user can use the editor. If the user can’t use the editor, there’s no reason for them to use our endpoint. This will prevent anonymous users (aka, “anyone on the internet”) from using our endpoint, possibly for purposes we don’t like.

    Now, let’s see our proxy function:

    There’s a bit going on here. First, we get the url variable from the request and run it through a helper function we wrote to make sure it is actually a DeviantArt URL. Then we use wp_remote_get to have the PHP backend make the request to DeviantArt’s oEmbed API. Because requests like this don’t have the extra considerations that a JavaScript request has, they are not usually subject to CORS. After some quick checking to make sure we have an actual response, we package up the response from DeviantArt inside a WP_REST_Response object and send it back to our block.

    Inside our block, we just have to call apiFetch to have WordPress automatically set up the request to our endpoint:

    Because apiFetch returns a Promise, we need to use async and await when using it. But that’s another blog post.

    You can see the whole thing in action in the finished plugin. It’s built using our own WDS Block Starter!

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Wordpress contact form 7 при отправке сообщения произошла ошибка пожалуйста попробуйте еще раз позже
  • Wordpress как изменить шрифт заголовка
  • Wordpress как изменить ширину шаблона
  • Wordpress как изменить шаблон рубрики
  • Wordpress как изменить цвет фона

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии