Pulling content from a WordPress feed using JavaScript

3

I found a interesting script that can help me a lot in the organization content.

The script below is used to pull content from a website through the blog feed. In this case, it's meant for use with Google's Blogspot feeds.

The script creator said it's possible to use it with a WordPress feed. What should I change to work on a WordPress blog?

<script type="text/javascript"> 
//<![CDATA[ 
var firsttime = 0;
var paginaactual = 1;
var postporpagina = 60;
var cantidadpaginas = 0;
var cantidadposts = 0;
var maxpaginas = 10;
var minpaginas = 5;

function showpageposts(json) {
  var entry, posttitle, posturl, postimg;
  var salida = "";
  if(cantidadpaginas==0) {
    cantidadposts = parseInt(json.feed.openSearch$totalResults.$t);
    cantidadpaginas = parseInt(cantidadposts / postporpagina) + 1;
  }
  for (var i = 0; i < postporpagina; i++) {
    if (i == json.feed.entry.length) { break; }
    entry = json.feed.entry[i];
    posttitle = entry.title.$t;
    for (var k = 0; k < entry.link.length; k++) {
      if (entry.link[k].rel == 'alternate') {
        posturl = entry.link[k].href;
        break;
      }
    }
    if ("media$thumbnail" in entry) {
      postimg = entry.media$thumbnail.url;
    } else {
      postimg = "http://3.bp.blogspot.com/_hljKDuw-cxQ/SsmfbhHhGrI/AAAAAAAAOU0/vCmT5Y4wzEo/s00/vagaPlantilla_resumenpostsnoimage.gif";
    }
    salida += "<div class='paginaposts'>";
    salida += "<a href='" + posturl + "' target='_blank'><img src='" + postimg + "' /></a>";
    salida += "<h6><a href='" + posturl + "' target='_blank'>" + posttitle + "</a></h6>";
    salida += "</div>";
  }
  document.getElementById("resultados").innerHTML = salida;
  paginacion();
}

function paginacion() {
  contadorP = 0;
  salida = "";
  if(paginaactual>1) {
    salida += "<a class='antesdespues' href='javascript:incluirscript(" + parseInt(paginaactual-1) + ")'>anterior</a>";
  } else {
    salida += "<span class='deshabilitado'>anterior</span>";
  }
  if (cantidadpaginas<(maxpaginas+1)) {
    for (contadorP = 1; contadorP <= cantidadpaginas; contadorP++){
      if (contadorP==paginaactual) {
        salida += "<span class='actual'>" + contadorP + "</span>";
      } else {
        salida += "<a href='javascript:incluirscript(" + contadorP + ")'>" + contadorP + "</a>";
      }
    }
  } else if(cantidadpaginas>(maxpaginas-1)) {
    if(paginaactual<minpaginas) {
      for (contadorP=1; contadorP<(maxpaginas-2); contadorP++){
       if (contadorP == paginaactual) {
         salida += "<span class='actual'>" + contadorP + "</span>";
       } else {
         salida += "<a href='javascript:incluirscript(" + contadorP + ")'>" + contadorP + "</a>";
       }
     }
     salida += " ... ";
     salida += "<a href='javascript:incluirscript(" + parseInt(cantidadpaginas-1) + ")'>" + parseInt(cantidadpaginas-1) + "</a>";
     salida += "<a href='javascript:incluirscript(" + cantidadpaginas + ")'>" + cantidadpaginas + "</a>";
    } else if(cantidadpaginas-(minpaginas-1)>paginaactual&&paginaactual>(minpaginas-1)) {
      salida += "<a href='javascript:incluirscript(1)'>1</a>";
      salida += "<a href='javascript:incluirscript(2)'>2</a>";
      salida += " ... ";
      for (contadorP=paginaactual-2; contadorP<=paginaactual+2; contadorP++) {
        if (contadorP==paginaactual) {
          salida += "<span class='actual'>" + contadorP + "</span>";
        } else {
          salida += "<a href='javascript:incluirscript(" + contadorP + ")'>" + contadorP + "</a>";
        }
      }
      salida += " ... ";
      salida += "<a href='javascript:incluirscript(" + parseInt(cantidadpaginas-1) + ")'>" + parseInt(cantidadpaginas-1) + "</a>";
      salida += "<a href='javascript:incluirscript(" + cantidadpaginas + ")'>" + cantidadpaginas + "</a>";
    } else {
      salida += "<a href='javascript:incluirscript(1)'>1</a>";
      salida += "<a href='javascript:incluirscript(2)'>2</a>";
      salida += " ... ";
      for (contadorP=cantidadpaginas-(minpaginas+1); contadorP<=cantidadpaginas; contadorP++) {
        if (contadorP==paginaactual) {
          salida += "<span class='actual'>" + contadorP + "</span>";
        } else {
          salida += "<a href='javascript:incluirscript(" + contadorP + ")'>" + contadorP + "</a>";
        }
      }
    }
  }
  if (paginaactual<contadorP-1) {
    salida += "<a class='antesdespues' href='javascript:incluirscript(" + parseInt(paginaactual+1) + ")'>siguiente</a>";
  } else {
    salida += "<span class='deshabilitado'>siguiente</span>";
  }
  document.getElementById("paginacion").innerHTML = salida;
  var iniciopagina = (paginaactual * postporpagina) - (postporpagina - 1);
  var finalpagina = paginaactual * postporpagina;
  var totales = "Total de entradas publicadas: " + cantidadposts + " - Mostrando entradas " + iniciopagina + " a " + finalpagina;
  document.getElementById("totales").innerHTML = totales;
}

function incluirscript(pagina) {
  if(firsttime==1) {removerscript();}
  document.getElementById("resultados").innerHTML = "<div id='loadingscript'>cargando ...</div>";
  document.getElementById("paginacion").innerHTML = "";
  document.getElementById("totales").innerHTML = "";
  var iniciopagina = (pagina * postporpagina) - (postporpagina - 1);
  var archivo = "http://vagabundia.blogspot.com/feeds/posts/default?start-index=" + iniciopagina;
  archivo += "&max-results=" + postporpagina;
  archivo += "&orderby=published&alt=json-in-script&callback=showpageposts";
  var nuevo = document.createElement('script');
  nuevo.setAttribute('type', 'text/javascript');
  nuevo.setAttribute('src', archivo);
  nuevo.setAttribute('id', 'TEMPORAL');
  document.getElementsByTagName('head')[0].appendChild(nuevo);
  firsttime = 1;
  paginaactual = pagina;
}

function removerscript() {
  var el = document.getElementById("TEMPORAL");
  var padre = el.parentNode;
  padre.removeChild(el);
}

onload=function() { incluirscript(1); }
//]]> 
</script>

And this is the CSS that comes with the script

<!-- Aquí ponemos los estilos en primer lugar --> 

<style>
.post-body {height: 2180px;}
  #resultados { 
width: 650px;}
  #loadingscript {color:#888;font-family:Century Gothic;font-size:100px;letter-spacing:-10px;text-align:center;text-shadow:-5px 0 1px #444;}
.post-body br {display: none;}
  /* estas son las reglas de estilo para las entradas */
   #resultados { /* el contenedor */
      margin: 0 auto;
      width: 600px;
  }
  #loadingscript { /* el texto o imagen de carga */ }
  .paginaetiquetas { /* cada una de las entradas */
    border: 1px solid #101921;
    height: 180px;
    margin: 13px 0;
    padding: 5px;
    width: 580px;
background:  #D3D3D3; 
  }
  .paginaetiquetas img { /* la miniatura */
    border: 1px solid #101921;
    float: left;
    height: 180px;
    padding-right: 1px;
    width: 145px;
  }
  .paginaetiquetas h6, .paginaetiquetas h6 a { /* los títulos de las entradas */
  font-family: 'Arial', Arial, Serif;
  font-weight: normal;
  text-decoration:none; color: #FFFFFF; 
  text-indent: 10px;
  font-size: 13px;
  margin: 25;
padding: 3px 0 0 0;margin:0; background: #191970;
  }
  .paginaetiquetas p { /* los resúmenes */
   overflow: hidden;
padding: 10px 10px 15px 10px;
font-size: 11px;
margin-bottom: 0px;
background-color: ;
border: 0px solid #DDD;

  }
  #navegadionetiquetas { /* el contenedor con los enlaces para navegar */
    border: 1px solid #404951;
    color: #BBB;
    font-size: 18px;
    text-align: center;
    margin:0 auto;
    width:314px;
  }

  /* estas son las reglas de estilo para la paginación inferior */
  #paginacion { /* el rectángulo contenedor */
    color: #333;
    font-family: Lucida Grande;
    font-size: 24px;
    font-weight: bold;
    height: 35px;
    line-height: 28px;
    padding: 20px 0;
    text-align: center;
  }
  #paginacion span, #paginacion a { /* cada número, texto o enlace */
    border: 1px solid #ccc;
    color: #191970;
    display: inline-block;
    font-family: Lucida Grande;
    font-size: 24px;
    font-weight: bold;
    margin: 0 2px;
    padding: 0 5px;
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
  }
  #paginacion span.actual { /* resaltamos la página actual */
    color: #000;
    padding: 0 5px;
    -moz-box-shadow: 0 0 30px #DDD inset;
    -webkit-box-shadow: 0 0 30px #DDD inset;
    box-shadow: 0 0 30px #DDD inset;
  }
  #paginacion a:hover { /* efecto hover sobre los enlaces */
    color: #990000;
    -moz-box-shadow: 0 0 20px #666 inset;
    -webkit-box-shadow: 0 0 20px #666 inset;
    box-shadow: 0 0 20px #666 inset;
  }
  #paginacion .antesdespues { border: none; }
  #paginacion .antesdespues:hover {
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
  #paginacion span.deshabilitado { /* los enlaces deshabilitados */
    border: none;
    color: #000;
  }

  /* la salida de la cantidad total */
  #totales {text-align:center;}
</style>

<!-- cargo el script --> 

<!-- los divs contenedores -->

<!-- aquí se mostrarán los posts --> 

<div id="resultados">
</div>

<!-- elimino flotaciones -->
<div style="clear: both;">
</div>

<!-- aquí se mostrará la paginación --> 
<div id="paginacion">
</div>

<!-- aquí se mostrará el texto con los totales  --> 
<div id="totales">
</div>
    
asked by anonymous 26.08.2014 / 00:21

1 answer

1

I find it very strange how this code reads the XML by putting it as the source of a script in the head of HTML markup.

var archivo = "http://example.com/feeds/posts/default?start-index=" + iniciopagina;
var nuevo = document.createElement('script');
archivo += "&max-results=" + postporpagina;
archivo += "&orderby=published&alt=json-in-script&callback=showpageposts";
nuevo.setAttribute('type', 'text/javascript');
nuevo.setAttribute('src', archivo);
nuevo.setAttribute('id', 'TEMPORAL');
document.getElementsByTagName('head')[0].appendChild(nuevo);

Searching, I found the tutorial Google Feeds API - jQuery plugin , which uses the Google Feed API and the jGFeed to read a feed and convert it to JSON (much easier than XML).

The following example includes the tutorial and jGFeed code. Just provide a URL of a WordPress feed that we received a JSON with the posts of the feed. So far as I know, the only query that can be tailored is start-index which corresponds to paged in WP.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>WordPress feed to JSON</title>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script></head><body><divid="resultados">
</div> 

<script>
/**
 * https://gist.github.com/psynewave/4220821
 */
(function($){
    $.extend({
        jGFeed : function(url, fnk, num, key){
            // Make sure url to get is defined
            if(url == null) return false;
            // Build Google Feed API URL
            var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
            if(num != null) gurl += "&num="+num;
            if(key != null) gurl += "&key="+key;
            // AJAX request the API
            $.getJSON(gurl, function(data){
                if( !data.responseData ) {
                    console.log('Erro 400: Feed could not be loaded.');
                    return;
                }
                if(typeof fnk == 'function')
                    fnk.call(this, data.responseData.feed);
                else
                    console.log('Erro: Função de callback não definida.');
            });
        }
    });
})(jQuery);

/**
 * http://jquery-howto.blogspot.com.es/2009/05/google-feeds-api-jquery-plugin.html
 */
var paged = 1;
$.jGFeed(
    'http://en.blog.wordpress.com/feed/?paged=' + paged,
    function(feeds){
        // Check for errors
        if(!feeds){
            // there was an error
            console.log('Erro: Não houve resposta do feed.');
        }
        // do whatever you want with feeds here
        for(var i=0; i<feeds.entries.length; i++){
            var salida = '';
            var entry = feeds.entries[i];
            salida += "<div class='paginaposts'>";
            salida += "<h6><a href='" + entry.link + "' target='_blank'>" + entry.title + "</a></h6>";
            salida += "</div>";
            $('#resultados').append(salida);
        }
    }, 
    10
);
</script>
</body>
</html>

/**
 * https://gist.github.com/psynewave/4220821
 */
(function($){
    $.extend({
        jGFeed : function(url, fnk, num, key){
            // Make sure url to get is defined
            if(url == null) return false;
            // Build Google Feed API URL
            var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
            if(num != null) gurl += "&num="+num;
            if(key != null) gurl += "&key="+key;
            // AJAX request the API
            $.getJSON(gurl, function(data){
                if( !data.responseData ) {
                    console.log('Erro 400: Feed could not be loaded.');
                    return;
                }
                if( typeof fnk == 'function' )
                    fnk.call(this, data.responseData.feed);
                else
                    console.log('Erro: Função de callback não definida.')
            });
        }
    });
})(jQuery);

/**
 * http://jquery-howto.blogspot.com.es/2009/05/google-feeds-api-jquery-plugin.html
 */
var paged = 1;
$.jGFeed(
    'http://matheuspiscioneri.com.br/feed/?paged=' + paged,
    parseFeed, 
    10
);

function parseFeed(feeds){
    // Check for errors
    if( !feeds ){
        // there was an error
        return false;
    }
    $('#resultados').html('');
    // do whatever you want with feeds here
    for(var i=0; i<feeds.entries.length; i++){
        var salida = '';
        var entry = feeds.entries[i];
        salida += "<div class='paginaposts'>";
        salida += "<h6><a href='" + entry.link + "' target='_blank'>" + entry.title + "</a></h6>";
        salida += "</div>";
        $('#resultados').append(salida);
    }
}

$('#refresh').click(function(){
    $(this).hide();
    $.jGFeed(
        'http://lorelle.wordpress.com/feed/?paged=' + paged,
        parseFeed, 
        10
    );
});
.paginaposts a{
    font-size: 2em;
    text-decoration: none
}
.paginaposts a:before {
    content: "
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="resultados">
</div> 

<button id="refresh">Outro feed</button>
FCC
var archivo = "http://example.com/feeds/posts/default?start-index=" + iniciopagina;
var nuevo = document.createElement('script');
archivo += "&max-results=" + postporpagina;
archivo += "&orderby=published&alt=json-in-script&callback=showpageposts";
nuevo.setAttribute('type', 'text/javascript');
nuevo.setAttribute('src', archivo);
nuevo.setAttribute('id', 'TEMPORAL');
document.getElementsByTagName('head')[0].appendChild(nuevo);
a0
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>WordPress feed to JSON</title>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script></head><body><divid="resultados">
</div> 

<script>
/**
 * https://gist.github.com/psynewave/4220821
 */
(function($){
    $.extend({
        jGFeed : function(url, fnk, num, key){
            // Make sure url to get is defined
            if(url == null) return false;
            // Build Google Feed API URL
            var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
            if(num != null) gurl += "&num="+num;
            if(key != null) gurl += "&key="+key;
            // AJAX request the API
            $.getJSON(gurl, function(data){
                if( !data.responseData ) {
                    console.log('Erro 400: Feed could not be loaded.');
                    return;
                }
                if(typeof fnk == 'function')
                    fnk.call(this, data.responseData.feed);
                else
                    console.log('Erro: Função de callback não definida.');
            });
        }
    });
})(jQuery);

/**
 * http://jquery-howto.blogspot.com.es/2009/05/google-feeds-api-jquery-plugin.html
 */
var paged = 1;
$.jGFeed(
    'http://en.blog.wordpress.com/feed/?paged=' + paged,
    function(feeds){
        // Check for errors
        if(!feeds){
            // there was an error
            console.log('Erro: Não houve resposta do feed.');
        }
        // do whatever you want with feeds here
        for(var i=0; i<feeds.entries.length; i++){
            var salida = '';
            var entry = feeds.entries[i];
            salida += "<div class='paginaposts'>";
            salida += "<h6><a href='" + entry.link + "' target='_blank'>" + entry.title + "</a></h6>";
            salida += "</div>";
            $('#resultados').append(salida);
        }
    }, 
    10
);
</script>
</body>
</html>
a0"; }
/**
 * https://gist.github.com/psynewave/4220821
 */
(function($){
    $.extend({
        jGFeed : function(url, fnk, num, key){
            // Make sure url to get is defined
            if(url == null) return false;
            // Build Google Feed API URL
            var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
            if(num != null) gurl += "&num="+num;
            if(key != null) gurl += "&key="+key;
            // AJAX request the API
            $.getJSON(gurl, function(data){
                if( !data.responseData ) {
                    console.log('Erro 400: Feed could not be loaded.');
                    return;
                }
                if( typeof fnk == 'function' )
                    fnk.call(this, data.responseData.feed);
                else
                    console.log('Erro: Função de callback não definida.')
            });
        }
    });
})(jQuery);

/**
 * http://jquery-howto.blogspot.com.es/2009/05/google-feeds-api-jquery-plugin.html
 */
var paged = 1;
$.jGFeed(
    'http://matheuspiscioneri.com.br/feed/?paged=' + paged,
    parseFeed, 
    10
);

function parseFeed(feeds){
    // Check for errors
    if( !feeds ){
        // there was an error
        return false;
    }
    $('#resultados').html('');
    // do whatever you want with feeds here
    for(var i=0; i<feeds.entries.length; i++){
        var salida = '';
        var entry = feeds.entries[i];
        salida += "<div class='paginaposts'>";
        salida += "<h6><a href='" + entry.link + "' target='_blank'>" + entry.title + "</a></h6>";
        salida += "</div>";
        $('#resultados').append(salida);
    }
}

$('#refresh').click(function(){
    $(this).hide();
    $.jGFeed(
        'http://lorelle.wordpress.com/feed/?paged=' + paged,
        parseFeed, 
        10
    );
});

Now it's a matter of printing the desired HTML and implementing the pagination that will be used in ?paged= . Check out the documentation to see other variants of possible feeds. You can also create custom feeds , and I believe you may need this if you want to implement postporpagina and orderby .

Finally, since I'm suggesting jQuery instead of JavaScript and a new way of reading the feed, I'll also suggest implementing a other pagination type and a other type of grid ;)

    
26.08.2014 / 01:36