14

Sep

Automatically inserting posts into WordPress from a XML feed

This post will show you how to insert a post into WordPress from a XML feed. I use this to populate my www.caniplay.co.uk website with products from the MediFusion feeds.

 

The posts are not finished when inserted, hence why I make them draft posts. They still need a category assigning to them and any other SEO type stuff I want to add.

 

What I do on www.caniplay.co.uk is attach this code to a hidden page and call it with a start date and end date. This will then add all the products from the feed within that date. I then go through each draft post, tidy it up and publish it to the site.

 

I find this the easiest way to add new posts to my site, as I just go into the drafts folder on WordPress and if there are posts in their I know they need tidying up and adding to the site.

 

UPDATE: I have now added to the code, it now also takes the associated JPG image and uploads that and also links it to the post you are creating. It does a quick check to make sure there is a image (some games have no image associated with them in the feed) and if there is a image URL then it uses it.

 

<?php

$xml = simplexml_load_file("http://www.find-games.co.uk/services/gamesearch.asp?mode=heavy&site=YOURTAGHERE&platform=ps3&category=consoles");

foreach ($xml->children() as $item)
{

	// Create post object
	$my_post = array(
		'post_title' => $item->groupTitle,
		'post_content' => $item->description . '[get_details ASIN="' . $item->id . '"]',
    	'post_status' => 'draft',
    	'post_author' => 1
	);

$new_post = wp_insert_post( $my_post );

if(!empty($item->imageURL))
{
	$file_url = media_sideload_image($item->imageURL,$new_post);
	echo $new_post . ' ' . $item->imageURL . ' ' . $file_url;
}
else
{
	echo $new_post;
}

?>
Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Tumblr Posterous Email Snailmail
Fork me on GitHub

28

Jun

Display Voucher Codes using the Buy.at API in PHP

This bit of PHP code will display all the Voucher Codes from the Buy.at network.

 

<?php

$xml = simplexml_load_file("https://users.buy.at/ma/index.php/affiliateVoucherCodes/list?handle=0&filter_status=y&include_pending=1&include_active=1&include_expired=0&prog_id=0&vertical_id=0&orderby=date_added&dir=desc&format=xml&email=USERNAME&password=PASSWORD");

echo '<table>';

echo '<tr>
        	<th scope="col">Retailer</th>
            <th scope="col">Description</th>
            <th scope="col">Voucher Code</th>
            <th scope="col">Start Date</th>
            <th scope="col">End Date</th>
            <th scope="col">Link</th>
        </tr>';

foreach($xml->body->children() as $child)
{
		if($child->status=='Active')
		{
			echo '<tr>';
			echo '<td>' . $child->programme . "</td>";
			echo '<td>' . $child->description . "</td>";
			echo '<td>' . $child->offer_code . "</td>";
			echo '<td>' . $child->start . "</td>";
			echo '<td>' . $child->end . "</td>";
			echo '<td><a href="' . $child->url . '" target="_blank" rel="nofollow" title="Visit website to use voucher code">Use Code</a></td>';
			echo '</tr>';
		}
}

echo '</table>';
?>

 
Remember to change the USERNAME and PASSWORD in the URL line to your own. There are also some parameters you can configure, I have it set to only show non-expired vouchers and in date order.

 
I use this code on my WP site, example here.
 

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Tumblr Posterous Email Snailmail

17

Jun

Fancy Easy Content Unit using JQuery, PHP and RSS

I wrote this as I was bored and fancied having a play with the ECU RSS feed option. Using the RSS feed part of a ECU the results are endless what you can do with it, your not tied to using the standard units that the ECU site supplies.

Get the main HTML file from here. What I did was view the demo in it’s own window, viewed the source code and copied and pasted into my code editor. Then you need to save the file as a .php file.
 

At the very top of the file, add this PHP code.

<?php
$xml = simplexml_load_file("http://www.easycontentunits.com/rss/6553/3/rss2full.rss");
?>

Remember to change the URL to match the easy content unit you want to use.

Then replace the “< div id=’sidebar’ >” with the code below.

<div id="sidebar">
<ul class="spy">
<?php
foreach ($xml--->channel->children() as $item)
{
	if($item->price!='')
	{
		echo '
	<li>';
		echo '<a title="View round" href="#"><img src="' . $item->image . '" alt="" width="70" height="70" /></a>';
		echo '
<h5><a title="View round" href="#">' . substr($item->title, 0, 30) . '</a></h5>
';
		echo '

' . substr($item->description, 0, 60) . '

';

		echo '

<a title="Buy this item" href="#">£' . strip_tags($item->price) . '</a>';
		echo '<a title="Buy this item" href="' . $item->link . '">Buy Now</a>

';
		echo '</li>
';
	}
}
?>
</ul>
</div>

You should then be able to upload the file then and view it, remember its a PHP file, so won’t run locally on your machine. also your host must support PHP (most do). My example is here.
 

If all is ok, you should then be able the put that div and where on page where you would like the ECU to appear.
 

I have been asked if this can be used in WordPress but unfortunately I have no experience of creating plug-ins for WordPress, so can’t answer that. All donations will be put to me buying books about WordPress, so you never know if I get enough donations, a WordPress plug-in could be next.

 


 

I may be able to answer some questions in the comments below, but am not a PHP or JavaScript guru.
 

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Tumblr Posterous Email Snailmail

8

Jun

Turning a Easy Content Unit into HTML using ASP.NET (Visual Basic)

Easy Content Units usually use JavaScript to write the contents of the unit on your webpage, the trouble with this method is that search engines have JavaScript switched off when they visit your website. This means they never see the contents on the easy content unit, if you have a page with not much content but a nice unit, search engines will not see a lot when they visit. Using the ASP.NET (VB) code below converts the unit and then writes it out to the page before the page is rendered. Because its using ASP.Net, no matter who visits the page, the ASP code will always run, so the easy content unit will be visible to all search engines.

These are the name-space libraries needed.

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>

I have put this in the page load section, so it only runs on page load. The way code works basically is by calling the unit and then stripping out all the JavaScript that writes to the page using document.write. This then leaves just the bare HTML which can then be written to the page along with any other HTML on the page.

Sub Page_Load(sender As Object, e As EventArgs)

	'Variable declarations
    Dim aSplit, i
    Dim sOutput As String
    Dim objResponse As WebResponse

	'Read the ECU into a variable using a HTTP request
    Dim objRequest As WebRequest = HttpWebRequest.Create("http://www.easycontentunits.com/js_unit.php?ecu_mid=1199&ecu_uid=50564")

	'Get the response from the above request
    objResponse = objRequest.GetResponse()

	'Convert the response into a string using text streaming
    Using sr As New StreamReader(objResponse.GetResponseStream())
        strResult = sr.ReadToEnd()
        sr.Close()
    End Using

	'We now need to get rid of all the JS code

    'Get rid of document.write(unescape("
    strResult = replace(strResult,"document.write(unescape(""","")

    'Get rid of ")
    strResult = replace(strResult,""")","")

    'Get rid of );
    strResult = replace(strResult,");","")

    ' next convert %hexdigits to the character
    aSplit = Split(strResult, "%")
    If IsArray(aSplit) Then
        sOutput = aSplit(0)
        For i = 0 to UBound(aSplit) - 1
            sOutput = sOutput & Chr("&H" & Left(aSplit(i + 1), 2)) & Right(aSplit(i + 1), Len(aSplit(i + 1)) - 2)
        Next
    End If

    'Move finished hex conversion back to original var name
    strResult = sOutput

End Sub

You put the code below on the page where you want the unit to appear.

<%Response.Write(strResult)%>
Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Tumblr Posterous Email Snailmail

5

Jun

How to read the Tumblr API in ASP.NET using Visual Basic

I written this bit of code for 2 reasons, first was to read whatever was posted onto a Tumblr blog and integrate it into a clients website. The other reason was if Tumblr was to go down, the blog page would still work due to the caching on the Tumblr data.

I always choose Tumblr when setting up a blog for a client where no one really looks direct at the blog, its more a easy way of letting the client create blog post and it magically appears on their website.

Anyway, enough rambling here is code. Please remember there is probably a million ways to do this and mine might not be the best but it works.

 

Header – This tries to load the XML from tumblr and store it in a file on the webserver. It then checks to see if a cached file/xml is present, if not it makes a cached file/xml out of the file stored on the webserver. The way the cache is created using a dependency, so if the file changes, the cache will change. It then loads the cached file/xml in a var called Posts.

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Linq" %>

Dim Posts As XElement
Sub Page_Load(sender As Object, e As EventArgs)

Try
'Read Tumblr Feed and save it locally
Dim xmlMasterUpdateDoc As New XmlDocument()
xmlMasterUpdateDoc.Load("http://*nameofyourtumblrblog*.tumblr.com/api/read")
xmlMasterUpdateDoc.Save("*somewhereonyourhostingspace*\blog.xml")

Catch xmlEx As XmlException
'Catch any XML error and display it.
Response.Write("XML Exception Thrown -> " + xmlEx.Message)

Catch eX As Exception
'Catch the error and display it.
Response.Write("Exception Thrown -> " + eX.Message)
Finally

End Try

If Cache("tumblrXE") is Nothing then

'There is no tumblrXE item in the Cache,  so load it from the local file
Dim tumblrResponse As XElement = XElement.Load("*somewhereonyourhostingspace*\blog.xml")

'Add it to the Cache and make it dependant on the local file (so it if changes the cache will)
Cache.Insert("tumblrXE", tumblrResponse, New CacheDependency("*somewhereonyourhostingspace*\blog.xml"))

End If

Posts = Cache("tumblrXE").Element("posts")

End Sub

This next bit of code, goes through all the posts and depending on the type displays them. I have only done regular, link and image post types.

<%
'if this value is 0, there are no posts.
If Posts.Attribute("total").Value <> "0" Then
'loop around all the posts
For Each itemElement As XElement In Posts.Elements("post")

If itemElement.Attribute("type") = "link" Then

Response.Write(itemElement.Attribute("date").Value)
Response.Write(itemElement.Elements("link-text").Value)
Response.Write(itemElement.Elements("link-url").Value)

End If

If itemElement.Attribute("type") = "photo" Then
          Response.Write(itemElement.Elements("photo-caption").Value)
          Response.Write(itemElement.Attribute("date").Value)
          Response.Write(itemElement.Elements("photo-link-url").Value)
          Response.Write(itemElement.Elements("photo-url").Value)
          Response.Write(itemElement.Elements("photo-caption").Value)
End If

If itemElement.Attribute("type") = "regular" Then
      Response.Write(itemElement.Elements("regular-title").Value)
      Response.Write(itemElement.Attribute("date").Value)
      Response.Write(itemElement.Elements("regular-body").Value)
End If

Next

End If

As I say, not sure if it’s the best way but it works for me so hopefully has given you a helping hand to implement your own solution.

Facebook Twitter Linkedin Digg Delicious Reddit Stumbleupon Tumblr Posterous Email Snailmail

Recent Tweets