Pulling content from a Wordpress feed using Javascript

Asked

Viewed 918 times

3

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

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

The creator of the script said it is possible to use it with a Wordpress feed. What should I change for it to work on a blog made Wordpress?

<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 accompanies 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>
  • 1

    What happens when you run the script pointing to a WP site?

  • Here’s the working script http://jsfiddle.net/s0p49kbg/ When I change the feed to one of wordpress, nothing appears, maybe it’s the wordpress feed that should be different

  • Makes a mistake of Resource interpreted as Script but transferred with MIME type application/rss+xml when it’s a WP feed... Unfortunately, it is a lot of code to debug what is happening, IE, You have to pass line by line to try to understand and adapt.

  • I will make an adaptation of this script to wordpress it is necessary to change the searched fields and everything else

1 answer

1

I think much strange the way this code reads XML by placing it as the source of a script in the head of Markup HTML.

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 API Feeds - jQuery plugin, who 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 code and jGFeed. Just provide a URL of a Wordpress feed that we receive a JSON with the feed posts. As far as I know, the only var query that can be adapted is start-index which corresponds to paged at 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>
<div id="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: "\0FCC\00a0\00a0";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="resultados">
</div> 

<button id="refresh">Outro feed</button>

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 view other variants of possible feeds. It is also possible create custom feeds, and I think you might need this if you want to implement postporpagina and the orderby.

Finally, since I am suggesting jQuery instead of Javascript and a new way to read the feed, I will also suggest implementing a other type of pagination and a another type of grid ;)

  • I changed the feed to this http://matheuspiscioneri.com.br/feed/ and nothing appears

  • Well, you managed to make the original script work with Blogger?

  • Yes - here it is http://jsfiddle.net/s0p49kbg/

  • This feed http://matheuspiscioneri.com.br/feed/? start-index works in the browser but not in the script???

  • I updated the answer. On a WP site is ?paged, would http://matheuspiscioneri.com.br/feed/? paged=2, but you don’t have enough posts for page 2.

  • The script worked, but it was very limited in the part of css, practically do not change almost anything, it is only possible to show a list with the titles, in case the script I passed, it is possible to show the image attached to the post, and format the title and text.

  • I’m sorry, I can’t give you a complete solution. I think the hardest is already done. Good luck!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.