How to enable wpautop for XMLRPC content

So, the default xmlrpc get_post function does not have any nice filters for you to use. The solution: roll your own XML-RPC callback!

Hook into xmlrpc_methods and add a custom method, in this case called post_autop. The array key will be the method name, and the value the method callback.

<?php
add_filter( 'xmlrpc_methods', 'wpse44849_xmlrpc_methods' );
/**
 * Filters the XMLRPC method to include our own custom method
 */
function wpse44849_xmlrpc_methods( $method )
{
    $methods['post_autop'] = 'wpse44849_autop_callback';
    return $methods;
}

Then we have our callback function, which will receive an array of $args. Which will do a few simple things: log the user in (validate username/password), then fetch the post we want, replace the text with an autop’d version, and return the post.

<?php
function wpse44849_autop_callback( $args )
{

    $post_ID     = absint( $args[0] );
    $username    = $args[1];
    $password    = $args[2];

    $user = wp_authenticate( $username, $password );

    // not a valid user name/password?  bail.
    if( ! $user || is_wp_error( $user ) )
    {
        return false;
    }

    $post = get_posts( array( 'p' => $post_ID ) );

    // no posts?  bail.
    if( empty( $post ) )
    {
        return false;
    }

    $post = $post[0];

    // the magic happens here
    $post->post_content = wpautop( $post->post_content );

    return (array) $post;
}

You can, of course, do any customization you want to the post before returning the value. Here is the above as a plugin.

I used a bit of Python to test this.

>>> import xmlrpclib as xmlrpc
>>> s = xmlrpc.ServerProxy('http://localhost/xmlrpc.php')
>>> post = s.post_autop(1, 'admin', 'password')
>>> post
# content of the post here as a Python dict

Leave a Comment