Perfect way to allow others to use your content or you can use to place an ad on your own site. It really does not have to be a WordPress site!
Here is the widget source that we will call hello-world.php:
<div style="
display:table;
border:3px solid #ccc;
border-radius:.5em;
padding:.5em;
margin:0 auto;">
We say:
<?php echo "Hello World"; ?>
</div>
To deliver the above content, we will need to add the below on same server as above hello-world.php:
<?php
$WidgetURL = 'https://example.com/hello-world.php';
header('Access-Control-Allow-Origin: *');
echo file_get_contents($WidgetURL);
?>
We will call the above hello-widget.php
Now at the WordPress site, we will add the below into a "custom html widget" (or in a template file for the geeks):
<div id="__my-hello-widget-container"></div>
<script type="text/javascript">
var divID = "__my-hello-widget-container";
var url = "https://example.com/hello-widget.php>";
var http = new XMLHttpRequest();
if(http)
{
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200)
{ document.getElementById(divID).innerHTML=http.responseText; }
}
http.open("GET",url,true);
http.send();
}
</script>
The __my-hello-widget-container value **must be the same in both places** (the div id value and the JavaScript variable divID value).
Also note, the id value must be unique to the web page it appears on. Using two underline characters at the start of the id value should make it unique on remote website your code is on. It is possible to have multiple widgets on the same page if the div id value and the JavaScript variable divID value are different/unique.
SPECIAL NOTE: If you wish to restrict domains that access your widget, replace this in your hello-widget.php:
header('Access-Control-Allow-Origin: *');
With this:
$allowed_domains = ['https://example.com', 'https://example1.com'];
if (in_array($_SERVER['HTTP_ORIGIN'], $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}