Posts tagged ‘WORDPRESS’

July 9, 2012

List recent WordPress Blog Posts with javascript

Last week we discussed listing recent blog posts in ASP.NET MVC using the SyndicationFeed class. One thing that I do not like about that solution is that it is server side, so this week we will look at getting the same functionality client side using javascript.

After searching a bit for existing solutions, I found that the Google Feed API is ideal for the task. It’s extremely simple to implement and provides the expected functionality.

The first step is to add the api to your page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"> </script>

Note that jQuery is not required for the api, but it will be used later in this document.

Next, load the Feed API with the google.load method.

<script type="text/javascript">
	google.load("feeds", "1")
</script>

Once the ‘feeds’ module is set up to be loaded, create a div that will act as a container for the blog post list.

<div id="feedContainer" ></div>

Lastly, with some simple javascript we can dynamically build a list of the feed items.

<script type="text/javascript">
	var feedUrl = "https://blog.yojimbocorp.com/feed/";
	var feedContainer=document.getElementById("feedContainer");
	
	$(document).ready(function() {
		var feed = new google.feeds.Feed(feedUrl);
		feed.setNumEntries(10);
		feed.load( function(result) {
			list = "<ul>";
			if (!result.error){
				var posts=result.feed.entries;
				for (var i = 0; i < posts.length; i++) { 
					list+="<li><a href='" + posts[i].link + "'target=_blank'" + "'>" + posts[i].title + "</a></li>";
				}
				list+="</ul>";
				feedContainer.innerHTML = list;
			}
			else {
				feedContainer.innerHTML = "Unable to fetch feed from " + feedUrl;
			}					
		});
	});
</script>

Once complete, your page should look similar to the following.

<!DOCTYPE HTML>
<html>
	<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
	<script type="text/javascript" src="http://www.google.com/jsapi"> </script>
	<script type="text/javascript">
		google.load("feeds", "1")
	</script>
	</head>
	<body>
		<div id="feedContainer" ></div>
		<script type="text/javascript">
			var feedUrl = "https://blog.yojimbocorp.com/feed/";
			var feedContainer=document.getElementById("feedContainer");

			$(document).ready(function() {
				var feed = new google.feeds.Feed(feedUrl);
				feed.setNumEntries(10);
				feed.load( function(result) {
					list = "<ul>";
					if (!result.error){
						var posts=result.feed.entries;
						for (var i = 0; i < posts.length; i++) {
							list+="<li><a href='" + posts[i].link + "'target=_blank'" + "'>" + posts[i].title + "</a></li>";
						}
						list+="</ul>";
						feedContainer.innerHTML = list;
					}
					else {
						feedContainer.innerHTML = "Unable to fetch feed from " + feedUrl;
					}
				});
			});
		</script>
	</body>
</html>

If your page requires additional information about each post (description, author, categories, etc), be sure to look into using feed.setResultFormat and google.feeds.Feed.JSON_FORMAT.

Advertisement
July 2, 2012

List recent WordPress Blog Posts in ASP.NET MVC

Recently I was tasked with adding a list of recent blog posts from our WordPress site inside of an ASP.NET MVC web site. The initial strategy was going to involve fetching from the RSS feed, but after discovering the WordPress supported XML-RPC, I decided to explore that route first.

Using XML-RPC was supposed to be easy considering there is an available .NET library for it created by Charles Cook. The task should have been further simplified because there are several C# WordPress wrappers available.

After spending time with a couple of the WordPress wrappers available, it quickly became clear that the process of updating the wrappers to comply with the latest version of WordPress would be far more work than it was worth; especially considering the scope of this task.

So it was back to the original strategy of creating an RSS reader specifically for WordPress. After digging around a bit, I thankfully stumbled across the Syndication Feed class that is available in .Net 4.0 and above.

The Syndication Feed class basically provides the quick and easy solution that I was looking for while exploring the XML-RPC route. It really turned out to be a lot easier than I thought it could ever be.

So let’s get started. For this, I will assume that you are using an existing MVC application.

The first step is to add a reference to System.ServiceModel to your project as this is where the Syndication Feed class resides.

The second step is to create a View Model that will define a List of SyndicationItem’s:

using System.Collections.Generic;
using System.ServiceModel.Syndication;

namespace MvcApplication1.Models
{
    public class FeedViewModel
    {
        public FeedViewModel()
        {
            Posts = new List<SyndicationItem>();
        }

        public List<SyndicationItem> Posts { get; set; } 
    }
}

And in the Controller, we will need to populate the list:

using System.Linq;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
using System.Xml;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new FeedViewModel();

            using (var reader = XmlReader.Create("https://blog.yojimbocorp.com/feed/"))
            {
                var feed = SyndicationFeed.Load(reader);
                foreach (var post in feed.Items.Take(10))
                {
                    model.Posts.Add(post);
                }
            }

            return View(model);
        }
    }
}

You will of course want to customize the reader URL to be your own and most likely will want to create a configuration entry for it.

And finally, display the data in your view:

@model MvcApplication1.Models.FeedViewModel
           
@foreach (var post in Model.Posts)
{
    <td><a href="@post.Id" target="_blank">@Html.DisplayFor(model => post.Title.Text)</a></td>
    <br />
    
}

I highly recommend reviewing the SyndicationItem documentation when creating your view.