Cross post code

Posted in Technicalon Mar 1, 2006

I’ve implemented a method which will automatically take posts I make on and publish them on this blog as well. I thought I would share the code I used to do this. If you were to use use this script, you would need to replace text in all caps with actual values.

My code makes use of the Blogger Class from Dented Reality. Use at your own risk and don’t blame me if it doesn’t work or screws up your blogs.

< ?php


$wp_host = 'WORDPRESS_HOSTNAME'; //ie.
$wp_rpc = 'WORDPRESS_PATH_TO_XMLRPC'; //ie. /blog/xmlrpc.php

$wordpress = new bloggerclient($wp_name, $wp_pass, $wp_host, $wp_rpc);
$blogger = new bloggerclient($b_name, $b_pass, '', '/api/RPC2');

$newposts = array_reverse($blogger->getRecentPosts($blogid, 3));



/**Database Structure:
CREATE TABLE imported (
  id int(11) NOT NULL auto_increment,
  blogid int(11) unsigned default NULL,
  postid bigint(20) unsigned default NULL,

foreach ($newposts as $post) {
    $sql = "SELECT * FROM imported ";
    $sql .= "WHERE blogid = $blogid and postid = {$post['postid']};";
    $result = mysql_query($sql);
    $n = mysql_num_rows($result);
    if ($n == 0) {
        $matches = array();
        $atom_api_url = "https://$b_name:$";
        $atom_api_url .= "/atom/$blogid/{$post['postid']}"
        $string = file_get_contents($atom_api_url);
        $regex = "||U";
        preg_match($regex, $string, $matches);
        $title = trim($matches[1]);
        if (!isset($title) || $title == '') {
            $title = "Blog entry for ". date('F jS');
        $insert = "INSERT INTO imported (blogid, postid) ";
        $insert .= "VALUES ($blogid, {$post['postid']});";
        $content = "". $post['content'];
        $wordpress->newPost(1, $content, true);

I also had to make a small change to the bloggerclient class in the class.blogger.php file. I changed the class constructor to allow a specified remote server. This was so I can use the same class with wordpress. My changes look like this:

    function bloggerclient($username, $password,$server=null, $path=null)
        if (isset($server)) $this->bServer = $server;
        if (isset($path)) $this->bPath = $path;

Comment Form