Giter Club home page Giter Club logo

wordpress-xmlrpc-client's Introduction

Wordpress XML-RPC PHP Client

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

A PHP client for Wordpress websites that closely implement the XML-RPC WordPress API

Created by Hieu Le

MIT licensed.

Current version: 2.4.2

All Important Features

  • Full test suit built in supporting testing using your own Wordpress site.
  • Support error logging to files with Monolog library. Now, erros can be logged in a more felxible way via error callbacks (v 2.4.0)
  • Support UTF-8 content.
  • Closely implement the whole XML-RPC WordPress API.
  • Detail exception will be thrown when errors occurs.
  • (v2.2) Support proxy and http authentication.
  • (v2.2.1) Allow value of DateTime class to be convert correctly to datetime.iso8601 XML-RPC type,
  • (v2.4.0) Support using custom User Agent string beside the default User Agent string.
  • (v2.4.0) Support callbacks on sending and error events

Installation

You will need Composer installed on your machine to use this library Composer now is not required but recommended. Verify that composer is installed by typing this command

composer --version

Choose one of the following methods to install Wordpress XML-RPC PHP Client

Your project has used composer:

Add this dependency into your composer.json file

"hieu-le/wordpress-xmlrpc-client":"~2.0"

After that, run composer update to install this package.

Your project does not use composer:

Clone or download the archive of this package from github. Include all files in the src directory into your project and start using Wordpress XML-RPC Client. You have to update the code of this library manually if using it without Composer.

Required PHP extension is xmlrpc extension. The curl extension is optional but recommended.

Usage

All API call will be executed via an instance of the WordpressClient class. Since version 2.4.0, there is no mandatory parameters in the contructor. endPoint, username, and password can be updated anytime by calling setCredentials method. The last parameter in previous version contructor (which is an instance of \Illuminate\Log\Writer class) is deprecated and will be removed in the next major release. Below is an example of using this library:

# Your Wordpress website is at: http://wp-website.com
$endpoint = "http://wp-website.com/xmlrpc.php";

# The Monolog logger instance
$wpLog = new Monolog\Logger('wp-xmlrpc');

# Create client instance
$wpClient = new \HieuLe\WordpressXmlrpcClient\WordpressClient();
# Log error
$wpClient->onError(function($error, $event) use ($wpLog){
    $wpLog->addError($error, $event);
});

# Set the credentials for the next requests
$wpClient->setCredentials($endpoint, 'username', 'password');

If you have used logging feture of previous version of this library, you should update your code to use the new way of loggin as above, the Monolog instance can be replaced by any kinds of logging tool that you have.

To use date time value, you must use an instance of DateTime class instead of a string.

There will be 2 types of exception may be thrown from this library:

  • XmlrpcException: this kind of exception will be thrown if there is an error when the server executing your request
  • NetworkException: this kind of exception will be thrown if there is an error when transfer your request to server or when getting the response.

For API reference, visit Wordpress documentation or Library API documentation

User Agent (since 2.4.0)

The library use the default User Agent when contacting with Wordpress blogs. If you want to use onother one, pass your custom User Agent string into the setUserAgent method. If you passed a falsy value (null, false, ...) the default one will be used (thank @WarrenMoore)

Callbacks and events (since 2.4.0)

The library allow developers to listen on two events Sending and Error. You can add new closure as a callback for each events by calling on<event> method with the closure as parameter (see the onError example above).

onSending($event)

This event is fired before each request is send to Wordpress blogs. $event is an array:

  • event: the name of the event, here is sending
  • endpoint: URL of the current endpoint
  • username: current username
  • password: current password
  • method: current XML-RPC method
  • params: parameters passed to the current method
  • request: the body of the current request which will be sent
  • proxy: current proxy config
  • auth: current http auth config

onError($errorMessage, $event)

This event is fired when the library run into errors, before any exception thrown. $errorMessage is a string. $event is an array:

  • event: the name of the event, here is sending
  • endpoint: URL of the current endpoint
  • request: the body of the current request
  • proxy: current proxy config
  • auth: current http auth config

Unit testing

By default, the project use recorded data as the default data for test suite. However, if you want to test with your own Wordpress installation, there are available options inside the ./tests/xmlrpc.yml file:

  • endpoint: the url of your Wordpress XML-RPC endpoint
  • admin_login: the email or username of a user with the Administrator role
  • admin_password: the password of the admin user
  • guest_login: the email or username of a user with the Subscriber role
  • guest_password: the password of the guest user

After update the ./tests/xmlrpc.yml file, run your test again.

wordpress-xmlrpc-client's People

Contributors

abdukhaligov avatar khanhicetea avatar letrunghieu avatar lracicot avatar mohit7610 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wordpress-xmlrpc-client's Issues

parse error. not well formed

I'm facing this error in the case whenever I want to update my wordpress post
"parse error. not well formed"
The data I'm passing to edit post is

$client->editPost( (int)$details['post_id'], $details['content'] )

where $details['post_id'] = my_post_id

and $details['content'] = ['post_title'=>'My new post title', 'post_content'=>'This is my new post content']

What am I doing wrong?
Thanks in advance

How to use the PHP client in Wordpress site?

Hi,

I want to setup this xmlrpc php client in my self hosted Wordpress site directly. I am a newbie and don't know how to install this?

Any pointers will be much appreciated.

Fill custom field when creating a new post

Hello,

I have rewrite the newPost function to add a custom field, but it doesn't work. Any idea? Thanks

function newPost($title, $body, array $content = array())
{
$default = array(
'post_type' => 'post',
'post_status' => 'publish',
'mykey' => 'myvalue',
);
$content = array_merge($default, $content);
$content['post_title'] = $title;
$content['post_content'] = $body;

    $content['custom_fields'] = array(
        'mykey' => 'myvalue',
    );

    $params = array(1, $this->_username, $this->_password, $content);

    return $this->_sendRequest('wp.newPost', $params);
}

Getting 'XML-RPC server accepts POST requests only'

Hi again,

Again been using the client successfully for months, now in the last few days I am getting this error in the _sendRequest() function:

XML-RPC server accepts POST requests only

This is the function, quite clearly using the POST method?

2015-01-16_08h59_27

The var_dump shows the below on execution:

image

Any idea guys?

Cheers,
Steve.

XML-RPC server accepts POST requests only

In my Laravel project, I want to publish content to WordPress blog. Everything works very well except for uploading media files. When I upload the file up to 850 KB, the file uploaded successfully. But when the file size exceeds 850 KB I get this error message XML-RPC server accepts POST requests only. And in my opinion this is unthinkable because I am using the same function to upload a file and the request method is always POST. This is my code.

$endpoint = $item->wp_url . '/xmlrpc.php';
$wpUser = $item->wp_username;
$wpPass = $item->wp_password;
$wpClient = new \HieuLe\WordpressXmlrpcClient\WordpressClient();
$wpClient->setCredentials($endpoint, $wpUser, $wpPass);

ob_clean();
$headers = get_headers($file->refe_file_path, TRUE);
$mimType = $headers['Content-Type'];
$output = '';

$handle = fopen($file->s3_file_path, 'r');

if ($handle) {
    while (!feof($handle)) {
        $output .= fread($handle, 1048576);
    }

    fclose($handle);
}

$uploadMedia = $wpClient->uploadFile($file->real_file_name, $mimType, $output, false);
$attachmentId = $uploadMedia['attachment_id'];

$content = [
    'post_type' => 'post',
    'post_status' => $request->input('post_status'),
    'post_title' => $title,
    'post_excerpt' => $request->input('post_excerpt'),
    'post_content' => $request->input('post_content'),
    'post_format' => $request->input('post_format'),
    'post_thumbnail' => $attachmentId,
    'terms_names' => [
          'category' => $request->input('post_category'),
           'post_tag' => $request->input('post_tags'),
    ],
    'post_author' => $request->input('post_author'),
];```

Encoding problems / wrong encoding

Please set in _sendRequest()

Change from:
$response = xmlrpc_decode($body);

To:
$response = xmlrpc_decode($body,"UTF-8");

Or best define the encoding.

XML-RPC accepts only POSTS

Wordpress Uncaught Network error: XML-RPC server accepts POST requests only. (Code: 405) wordpress

Since the newest Wordpress Update i get always this Error Message. Wordpress make this now correct.

How to solve this?

Upload file Exception

Hi,

I have an Exception when I want to upload an image. I think Wordpress changed their code. I use 4.5.1.

[HieuLe\WordpressXmlrpcClient\Exception\XmlrpcException] Could not write file (Empty filename)

SSL Certificate Problems

Hola, he encontrado la necesidad de modificar una parte de tu codigo para solucionarlo
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
ya que sin esto los dominios con https no funcionan como deberia

private function requestWithCurl()
{
$ch = curl_init($this->endPoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->request);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
if ($this->proxyConfig != false) {
if (isset($this->proxyConfig['proxy_ip'])) {
curl_setopt($ch, CURLOPT_PROXY, $this->proxyConfig['proxy_ip']);
}
if (isset($this->proxyConfig['proxy_port'])) {
curl_setopt($ch, CURLOPT_PROXYPORT, $this->proxyConfig['proxy_port']);
}
if (isset($this->proxyConfig['proxy_user']) && isset($this->proxyConfig['proxy_pass'])) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD,
"{$this->proxyConfig['proxy_user']}:{$this->proxyConfig['proxy_pass']}");
}
if (isset($this->proxyConfig['proxy_mode'])) {
curl_setopt($ch, CURLOPT_PROXYAUTH, $this->proxyConfig['proxy_mode']);
}
}
if ($this->authConfig) {
if (isset($this->authConfig['auth_user']) && isset($this->authConfig['auth_pass'])) {
curl_setopt($ch, CURLOPT_USERPWD,
"{$this->authConfig['auth_user']}:{$this->authConfig['auth_pass']}");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
if (isset($this->authConfig['auth_mode'])) {
curl_setopt($ch, CURLOPT_HTTPAUTH, $this->authConfig['auth_mode']);
}
}
$response = curl_exec($ch);
if (curl_errno($ch)) {
$message = curl_error($ch);
$code = curl_errno($ch);
$this->error = "curl: {$message} ({$code})";
$this->logError();
curl_close($ch);
throw new Exception\NetworkException($message, $code);
}
$httpStatusCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpStatusCode >= 400) {
$message = $response;
$code = $httpStatusCode;
$this->error = "http: {$message} ({$code})";
$this->logError();
curl_close($ch);
throw new Exception\NetworkException($message, $code);
}
curl_close($ch);

    return $response;
}

Extending the API

In wordpress, it is possible to extends the API by adding available methods. There is also some plugins to do it. Example: https://wordpress.org/plugins/extended-xml-rpc-api/

It would be interesting if could also extends this client. A very simple way I saw could be to change the visibility of the _sendRequest() method to protected. A more complicated (but cleaner) way could be to separate in two classes what I call "the frontend" of the client (the method we can call) and the "API connector" (all the request and curl stuff).

If the feature is accepted I may send a pull request whenever I have the time.

All methods return null

I'm noticing that all methods return null regardless of what the documentation says the return type should be. I am also noticing that file uploads are not working properly. What is going on?

How to add tags to a post?

I tried the following they don't work.

$wpClient->newPost($title, $message, array('terms' => array('category' => array($category)), 'mt_keywords' => 'tag'));

$wpClient->newPost($title, $message, array('terms' => array('category' => array($category)), 'mt_keywords' => array('tag')));

using your 2.0 api, worpress are blaclisting me

Hello, when I use your 2.0 version of your client, my wordpress blog are banning me, with this message :

<h2>You don't have permission to access this server.</h2>
        <p>Your IP address <code>{myIP}</code> has been blacklisted due to suspicious behaviour.</p>

Get always the Last 10 Posts (Published & Draft)

I don't know whether it is because of my Code, The Client or Wordpress.
But i get always the last 10 posts wherever which limit is set.
And in this posts are the draft and published.

My Code:

function getLastNews($number = 1, $offset = 1)
{
  $endpoint = "https://sub.domain.tld/xmlrpc.php";

  $wpClient = new \HieuLe\WordpressXmlrpcClient\WordpressClient();

  $wpClient->setCredentials($endpoint, 'OneOfMillionUser', 'myverystrongmysterysecretkey');

  $return = $wpClient->getPosts(array('post_type' => 'post', 'post_status' => 'published', 'offset' => $offset, 'number' => $number, 'orderby' => 'date', 'order' => 'DESC'));

  return $return;
}

I think this is correct. It have works a long time(PHP 5.6, i work an the develop Machine with PHP 7). :/
Instead number I have numberposts and tried posts_per_page.

Just started throwing an NetworkException "failed to open stream: HTTP request failed!"

Hi,

I've been using your client for a number of months, today however a user spotted that the "Blog" page isn't working, on debugging I discovered that WordpressClient::_sendRequest is throwing a NetworkException, the contents of error_get_last being:

'type' => int 2
'message' => string 'file_get_contents(http://benefitsevolution.wordpress.com/xmlrpc.php) [function.file-get-contents]: failed to open stream: HTTP request failed! ' (length=184)
'file' => string 'C:\wamp\www\Symfony_2_3_3\src\Starthere\WordpressBundle\XMLRPCClient\WordpressClient.php' (length=88)
'line' => int 623

Nothing has changed on my test server (which is exhibiting the same error as production) and no WP updates have been applied to the WP blog in the last 3 weeks, although it's unclear when the problem started occuring, any ideas?

Thanks, Steve.

i have an error with wordpress_xmlrpc on python

i have an error with wordpress_xmlrpc on python

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost

from wordpress_xmlrpc.methods.users import GetUserInfo

wp = Client('http://mysite.wordpress.com/xmlrpc.php', 'username', 'password')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in
wp = Client('http://mysite.wordpress.com/xmlrpc.php', 'username', 'pasword')
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\site-packages\wordpress_xmlrpc\base.py", line 24, in init
self.supported_methods = self.server.mt.supportedMethods()
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1112, in call
return self.__send(self.__name, args)
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1452, in __request
verbose=self.__verbose
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1154, in request
return self.single_request(host, handler, request_body, verbose)
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1170, in single_request
return self.parse_response(resp)
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 1336, in parse_response
p.feed(data)
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\xmlrpc\client.py", line 439, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 222

Remove limitation on closures

The current implementation (in 2.4.0) of WordPressClient::_logError() requires callbacks to be closures or function strings. Thus it is not possible to attach a class method as callback, which would make it easier to separate the callback from a logger.

However, if the callbacks would called instead by call_user_func_array() any callable type would be possible:

    private function _logError()
    {
        $callbacks = $this->_getCallback('error');
        $event = array(
            'event'    => 'error',
            'endpoint' => $this->_endPoint,
            'request'  => $this->_request,
            'proxy'    => $this->_proxyConfig,
            'auth'     => $this->_authConfig,
        );
        foreach($callbacks as $callback)
        {
            call_user_func_array($callback, array($this->_error, $event));
        }
    }

All calls are returning HTML

I have a self hosted (localhost) WP 4.3 install. All calls are returning HTML and not XML.

What am I doing wrong?

here's my code:

        $wpClient = new \HieuLe\WordpressXmlrpcClient\WordpressClient('wp.dev', 'erin', 'correct_password');

        $pages = $wpClient->getPosts(array('post_type'=> 'page'));
        $types = $wpClient->getPostTypes();

optional curl_setopt settting i.e. for proxy support

Since a6378f2 there is curl support.

Can you please make optional curl_setopt settings available when using curl i.e. to use a proxy.

curl_setopt ($ch, CURLOPT_PROXY, $proxy);
curl_setopt ($ch, CURLOPT_PROXYUSERPWD, $proxyuser);

Since _requestWithCurl() is private I don't see how to do that without changing the core.

Insufficient arguments passed to this XML-RPC method.

I am trying to make a new Post and it throws me this error "Insufficient arguments passed to this XML-RPC method."

$wpClient = new WordpressClient($domain->url, $domain->user, $domain->password);
$wpClient->newPost('Tittle', 'Content');

The getProfile method works fine, so there is no problem with the credentials

Can anyone help me with this?
Thanks in advance

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.