Mostrar un post al azar

Lo he visto en PurpleMoggy´s y me ha llamado la atención, aunque no le encuentro demasiada utilidad, la verdad, pero es una cosilla más para lucir en el blog. Podemos hacerlo mediante un script que añadiremos antes del cierre </head> de nuestra plantilla:


<script type='text/javascript'>
//<![CDATA[
var _yourBlogUrl = "http://NOMBREDETUBLOG.blogspot.com";

function randomPost() {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
var theUrl = _yourBlogUrl +"/feeds/posts/summary?alt=json-in-script&callback=getTotalPostsCallback&start-index=1&max-results=1";
script.setAttribute("src", theUrl);
document.documentElement.firstChild.appendChild(script);
};
function getTotalPostsCallback(json) {
var totalResults = json.feed.openSearch$totalResults.$t;
if (totalResults > 0) {
getRandomPostNumber(totalResults);
}
};
function getRandomPostNumber(totalResults) {
var randomNumber = Math.floor((Math.random() * totalResults) + 1);
getRandomUrl(randomNumber);
};
function getRandomUrl(randomNumber) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
var theUrl = _yourBlogUrl +"/feeds/posts/summary?alt=json-in-script&callback=getTheUrlCallback&start-index=" + randomNumber + "&max-results=1";
script.setAttribute("src", theUrl);
document.documentElement.firstChild.appendChild(script);
};
function getTheUrlCallback(json) {
var theUrl;
for(var i = 0; i < json.feed.entry[0].link.length; i++) {
if (json.feed.entry[0].link[i].rel == "alternate") {
theUrl = json.feed.entry[0].link[i].href;
break;
}
}
if(theUrl) {
window.location.href = theUrl;
}
}
//]]>
</script>

Cambiamos donde pone http://NOMBREDETUBLOG.blogspot.com por la url (dirección) de nuestro blog.

Añadimos un nuevo elemento html-javascript y pegamos esto:
<a href="javascript:randomPost();">View Random Post</a>

En "View Random Post" ponemos lo que queremos mostrar en el link hacia nuestro post al azar, por ejemplo podemos poner "Ver post al azar".

También podríamos colocar una imagen sustituyendo "View Random Post" por la url de la imagen escogida: <img src="url_de_la_imagen"/>, incluso usar las dos cosas (imagen y texto), por ejemplo un pequeño icono tipo flechita, solo tenemos que colocar la url de la imagen y a continuación el texto.

0 comentarios:

Publicar un comentario