Monthly Archives: July 2015

Using XMLRPC to get a List of Posts from WordPress

Today I'm going to demonstrate how one can go about remotely fetching a list of posts for any post type including custom post types remotely using XML-RPC in WordPress. What I thought was going to be a simple task ended up taking me the majority of an entire day to work out yesterday, so I am posting my solution here for future reference and to help others solve the same problem.

So during my quest to figure out a solution for listing posts for a remote WordPress blog inside the wp-admin of another WordPress blog, I came across a couple promising functions such as wp.getPosts, blogger_getRecentPosts and similar existing XML-RPC functions that reside within wp-includes/class-IXR.php. None of those did the trick however, so below is the final solution I came up with which involves extending the XML-RPC class noted.

Extending the XML-RPC functions in WordPress

Here's what you can add to your theme's functions.php or plugin file to extend the class-IXR.php class to allow remote listing of post titles for any given registered post type:

function wp_getTits() {
// Get the 'Profiles' post type
/*$args = array(
    'post_type' => 'oils-blends',
);*/
$args = array(
'nopaging' => true,
'numberposts'    => 300,//increase if more than 300 products exist!
'post_type'        => 'oils-blends',
'post_status'   => 'publish'//only exporting published products!
);
$loop = new WP_Query($args);
$tits = "";
while($loop->have_posts()): $loop->the_post();

$titis = get_the_title();
$tits .= $titis."zxz";

endwhile;
wp_reset_query();
return $tits;
}

function wp_new_xmlrpc_methods( $methods ) {
    $methods['wp.getTits'] = 'wp_getTits';
    return $methods;   
}
add_filter( 'xmlrpc_methods', 'wp_new_xmlrpc_methods');

After you add the above code to functions.php or your plugin file, then you can use the following block of code within a plugin file of another WordPress site to remotely list the posts of a WordPress blog on another server. I added the following code inside my plugin which was used to post to a remote WordPress site. I needed to read the existing posts in order to know whether to write or update the posts that I was pushing to the second blog:

<?php
echo "<p>Starting to get posts from remote website...</p><h3>List of Titles:</h3>";

$rpcurl = "http://example.com.au/wordpress_dir/xmlrpc.php";

$request = xmlrpc_encode_request('wp.getTits','1');
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
//echo "Curl results: $results<hr />";
curl_close($ch);
//separate titles by zxz string:
$titleArray = explode("zxz",$results);
    foreach($titleArray as $curTit){
        echo "$curTit<br />";
    }//END FOREACH TITLE
echo "<p>Finished...</p>";

?>

That's all folks. Now you can remotely fetch posts from one WordPress site to another without any prior knowledge of post IDs etc. Now if you do know the post IDs, then you could use the existing XML-RPC method, wp.getPost which uses the post ID as an argument. I'll share this code with you too even though it wasn't the final solution for me, it could work for someone that happens to know the post IDs for which they need to grab remotely. The following code was tested and working as of WordPress version 4.2.3:

Listing Posts Remotely using wp.getPost

As you will see, it is a lot easier to get post data when you know the post ID. Here is all you have to add to your WordPress plugin file to remotely grab a post using wp.getPost when you know the post's ID:

<?php
echo "<p>Starting to get post data from remote site...</p>";

$rpcurl = "http://example.com.au/wordpress_dir/xmlrpc.php";
$username = 'admin';
$password = 'password';
$post_id = 2820;
include('../wp-includes/class-IXR.php');  
        $client = new IXR_Client($rpcurl);
     
        $USER = $username;
        $PASS = $password;
               
        if (!$client->query('metaWeblog.getPost',$post_id, $USER,$PASS))
        {  
            echo('Error occurred during getting post.' . $client->getErrorCode().":".$client->getErrorMessage());  
        }
        $post = $client->getResponse();
       
        var_dump($post);
echo "<hr /><p>Finished....</p>";
?>

Of course you have to edit the URL, username and password above, but after that it will work fine.

Summary

So I've given you two ways to get post data from WordPress sites remotely. If you know the post IDs, then use the last method which is simpler, otherwise you have to extend the class explained above using the first two code snippets on this page. Good luck!

Fixing Encoding Problems When Creating WordPress Posts With PHP

I'm documenting this simple fix because it took me over an hour to figure out. I was writing a WordPress plugin that would publish custom post types from one blog to many others. In doing so, I used PHP to write code that would read posts from the master blog and write them to another blog, or several blogs actually. The problem was that some characters such has hyphens and the letter y would end up encoded incorrectly in the blog that the post was copied to. Here's two images that show what happened. The first is an image of the WYSIWYG editor in WordPress when viewing the post in the edit screen using the text tab. The second image is when viewing the post in the HTML tab of the WYSIWYG editor:

txt htm...so as you can see in the areas I've circled above, there is definitely something wrong with the character encoding happening somewhere.

Fixing Character Problems in WordPress and PHP

The solution was to use the following line of code on the post text before writing it to the WordPress database:

$txt = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $txt);

By using the PHP iconv function to convert the txt variable to a new encoding, I was able to stop the encoding problem and all was great! I'm not going to explain this in detail because frankly the finer details of PHP and HTML encoding elude me to this day after coding for over 15 years. I understand we need different encoding for different languages, but why can't we have more of a standard? It would make life so much easier!

Summary

I hope this helps someone as it did me. Good luck with your own encoding problem. I find it is often necessary to play with several PHP encoding functions to solve various problems, so if this doesn't do the trick, try htmlentities or utf8_encode and similar PHP functions to modify your text.

How to Connect to Ad Hoc Network from Windows 8.1

Microsoft seems to have dropped the ball on this one folks. For some unknown-to-me reason, Windows 8 computers cannot detect an ad hoc network. This means that when I set up an ad hoc internet sharing network on my Windows 7 laptop so that I could share the laptop's internet connection with a different laptop running Windows 8.1, it couldn't be done. The main reason it wouldn't work is because the ad hoc network I created does not show up under WiFi connections on the Windows 8.1 machine. I tried all sorts of things and only one finally worked, so I'll share it with you below. For anyone following my series on developing a Smart Home, This is the method I used to network my smart home PC to other PCs in the house. The laptop used as a controller for the house was connected directly to the cable modem using an Ethernet cable. Then I created an ad hoc network on the same laptop that broadcasts the internet signal(shares its internet connection) to any other computer in the house that has wireless capability.

Instructions for using ad hoc with Windows 8.1

  1.  First create your ad hoc connection from a computer that has a working internet connection that you want to share. FYI, Windows 7 starter does not have the ability to create ad hoc networks and won't allow you to share internet connections in any way without doing some serious mods to your OS. It's easier to use a PC that doesn't have Windows 7 starter.
  2. Next, on the machine that you want to share with that's running Windows 8.1 or similar, open the Control Panel and click on "Network and Sharing Center".
  3. Click on "Set up a new connection or network".
  4. Select "Manually connect to a wireless network" and click "Next".
  5. In the "Network Name" field, enter the ssid name for the network you created on the other computer exactly how you entered the name when you created the ad hoc network.
  6. Select he appropriate security type and enter a security key if needed.
  7. Be sure that the box that reads "Start this connection automatically" is NOT CHECKED. I normally leave the other box unchecked as well.
  8. Click the "Next" button.
  9. Close that window and open a command prompt window which you can do by hitting the windows key then clicking on the search icon(magnifying glass) in the upper right corner of the screen then typing "cmd" and searching. Click on the command prompt option from the search results to open a new command prompt window.
  10. At the command prompt, type(without quotes):"netsh wlan connect [ssid]" replacing [ssid] with the ssid name of the ad hoc network you created on the other PC.
  11. Now your Windows 8.1 PC is all set up to use that single ad hoc network. Unfortunately you'll have to repeat the above process for any other ad hoc networks you might want to use in the future. You'll not have to do it again for the same network though. Finally, to connect, all you do it type this at the command prompt: "netsh connect [ssid]" without quotes and replacing [ssid] with the ad hoc network name.
  12. Now you are connected, so use it til done and when you want to disconnect, you can use "netsh wlan disconnect " without quotes.
  13. If you ever wish to delete the ad hoc network from your Windows 8.1 computer, use this command from a command prompt: "netsh wlan delete profile [ssid] " without quotes and replacing the ssid name and brackets with actual network name.

There you go! Now you can connect your Windows 8.1 machine to an ad hoc network. It's really only about ten easy steps so don't be intimidated by my long explanation. Simple do the above one step at a time and you'll get it in no time at all. Good Luck!

Why Would You Use an Ad Hoc Network?

The reason I did this instead of using a WiFi wireless router was to save electricity. Since I had to have the main computer that controls the house running all the time anyway, I figured why not use it for a router too. I have effectively eliminated one small appliance which means saving about 10 watts of power continuously in my case.

Another reason could be that you simply do not have a wireless router. In my particular case, I fried mine last night by accidentally hooking 24 volts to the router instead of the required 12 volts. So this turned out to be a blessing in disguise because now I am able to save power on my Smart Home system and cut down on the number of wires as well.