Your sites Log in Sign up Menu

How do I embed a link to a random post in my template?

I'd like to add a section to my site which displays a link to a random post. What's the best way to accomplish that?


2 years ago, 1 replies   Improve this question

Try adding this to a page, or to a view in your template:

<p>Random post:</p>
<p id="insert_random"></p>
<script>
getRandomEntry(function (err, entry) {
  renderEntry(document.getElementById("insert_random"), entry);
});

function renderEntry(node, entry) {
  node.innerHTML = `<a href="${entry.url}">${entry.title}</a>`;
}

function getRandomEntry(callback) {
  var request = new XMLHttpRequest();
  var data;

  request.open("GET", "/random?json=true", true);

  request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
      data = JSON.parse(request.responseText);
      callback(null, data.entry);
    } else {
      callback(new Error("Failed to get random entry"));
    }
  };
  request.send();
}
</script>
Answered 2 years ago ยท Improve this answer

Privacy Terms