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

Overview

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:

onError(function($error, $event) use ($wpLog){ $wpLog->addError($error, $event); }); # Set the credentials for the next requests $wpClient->setCredentials($endpoint, 'username', 'password'); ">
# 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 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.

Comments
  • All methods return null

    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?

    opened by ryanschott 7
  • Insufficient arguments passed to this XML-RPC method.

    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

    opened by eduardodgarciac 5
  • Get always the Last 10 Posts (Published & Draft)

    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.

    opened by Huskynarr 5
  • Just started throwing an NetworkException

    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.

    opened by starthereau 4
  • XML-RPC accepts only POSTS

    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?

    opened by Huskynarr 3
  • The requested PHP extension xmlrpc is missing from your system.

    The requested PHP extension xmlrpc is missing from your system.

    I can not install your package. I got a message: The requested PHP extension xmlrpc is missing from your system.

    Please help me!! Thank you very much.

    opened by phuclh 3
  • Getting 'XML-RPC server accepts POST requests only'

    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.

    opened by starthereau 3
  • How to use the PHP client in Wordpress site?

    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.

    question 
    opened by athirukk 3
  • Post_date && Any Other Date Values in  private function _sendRequest

    Post_date && Any Other Date Values in private function _sendRequest

    private function _sendRequest are passed as strings and not defined as a date, WP will not accept these!

    Our Temp fix was xmlrpc_set_type($params[3]['post_date'],'datetime');

    bug 
    opened by scopefragger 3
  •  $wpClient->newTerm(); add new term in taxonomy use  file WordpressClient.php show error

    $wpClient->newTerm(); add new term in taxonomy use file WordpressClient.php show error

    Fatal error: Call to undefined function HieuLe\WordpressXmlrpcClient\xmlrpc_encode_request() in E:\VERTRIGO_SERVER\www\convert_rpc\WordpressClient.php on line 901

    opened by thanhlvkc 2
  • introduce protected method for accessing request body from WordpressClient subclass

    introduce protected method for accessing request body from WordpressClient subclass

    Sorry for the pull request spam. I just realised that there is no way to access the contents of _request, which is vital for subclassing WordpressClient. This patch adds a protected method to do just that.

    opened by igorwwwwwwwwwwwwwwwwwwww 2
  • XML-RPC server accepts POST requests only

    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'),
    ];```
    opened by sanasar-dev 1
  •  Getting Error Uncaught XML-RPC error: Invalid post ID (Code: 404).

    Getting Error Uncaught XML-RPC error: Invalid post ID (Code: 404).

    Dear Team,

    Thanks for making an awesome script for the wordpress XMLRPC library but I have an issue with the script, sometimes it working very smoothly but sometimes, it throwing some errors. can you tell me how to solve the Invalid POST ID error? xml rpc error

    opened by keyurvala 0
  • Fixes the HTTP/1.1 417 Expectation Failed Bug

    Fixes the HTTP/1.1 417 Expectation Failed Bug

    Fixes the "Expect: 100-continue" issue on some endpoints. Error example:

    Uncaught Network error: Expectation Failed The expectation given in the Expect request-header field could not be met by this server. The client sent

    Expect: 100-continue Only the 100-continue expectation is supported.

    (Code: 417) thrown in /var/www/html/vendor/hieu-le/wordpress-xmlrpc-client/src/WordpressClient.php on line 999

    opened by yvan02 0
  • i have an error with  wordpress_xmlrpc on python

    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

    opened by dido97 1
  • throw an error if response is larger than a limit of 10MB for libxml 2.7.9+

    throw an error if response is larger than a limit of 10MB for libxml 2.7.9+

    As Alwin commented at http://php.net/manual/en/function.xmlrpc-decode.php: screenshot_166 there is a limit of 10M for response it it exceeded xmlrpc_decode() will return NULL and most of programmers will not know what they do wrong, i spend all day for understand it :) So, i think it can be loged or cathed by this extension and throw an error that max size of response exceeded.

    opened by igorveremsky 0
Releases(2.6.0)
Owner
Hieu Le
Hieu Le
List of high-ranking websites powered by WordPress (everything but news and blogs)

Powered By WordPress About 25% of the web is powered by WordPress. A big majority of these sites are private blogs but also heavy-weights such as Sony

MB 19 Dec 23, 2022
Deploy WordPress websites with ease.

WordPress Deployer Deploy WordPress websites with ease. This package is basically a Deployer "recipe" for WordPress websites. Installation composer re

Happy Medium 2 Nov 12, 2022
A curated list of Awesome WordPress Theme, Plugins and Framework development Resources and WordPress Communities.

Awesome WordPress A curated list of Awesome WordPress Theme, Plugins and Framework development Resources and WordPress Communities. Inspired by bayand

Dropndot Limited 91 Dec 26, 2022
The Pronamic WordPress Basecone plugin allows you to connect your WordPress installation to Basecone.

Pronamic WordPress Basecone The Pronamic WordPress Basecone plugin allows you to connect your WordPress installation to Basecone. Table of contents Au

Pronamic 1 Oct 19, 2021
A WordPress plugin to suspend WordPress sites automagically. Simple and lightweight, no annoying ads and fancy settings.

Suspend WP A WordPress plugin to suspend WordPress sites automagically. Simple and lightweight, no annoying ads and fancy settings. ?? Demo (coming so

Waren Gonzaga 3 Nov 15, 2021
Twenty Twenty-Two, the default WordPress theme that will launch with WordPress 5.9.

Twenty Twenty-Two Welcome to the development repository for the default theme that will launch with WordPress 5.9. About Twenty Twenty-Two is designed

null 414 Nov 28, 2022
Easy handle APlayer on WordPress. A shortcode for WordPress to using APlayer.

Description Easy handle APlayer on WordPress. A shortcode for WordPress to using APlayer. Support [audio] tag, compatible with AMP. Requirement WordPr

Karl Chen 24 Nov 3, 2022
WordPress plugin that lets you use Discourse as the community engine for a WordPress blog

WP Discourse Note: the wp-discourse plugin requires >= PHP-5.4.0. The WP Discourse plugin acts as an interface between your WordPress site and your Di

Discourse 497 Dec 10, 2022
WordPress & TypeScript. Simple starter template for WordPress projects

WordPress & TypeScript. Simple starter template for WordPress projects that want to use TypeScript in combination with @wordpress/scripts

Make it WorkPress 11 Sep 27, 2022
Simple WordPress plugin to learn how to understand WordPress Crons and the Action Scheduler library.

Simple WordPress plugin to learn how to understand WordPress Crons and the Action Scheduler library. Import Jamendo playlists with tracks in WordPress posts.

Pierre Saikali 3 Dec 7, 2022
:rocket: GraphQL API for WordPress

WPGraphQL WPGraphQL is a free, open-source WordPress plugin that provides an extendable GraphQL schema and API for any WordPress site. Below are some

WPGraphQL 3.4k Jan 5, 2023
A WordPress package for updating custom plugins and themes based on an API response from a custom update server.

WordPress Update Handler A WordPress package for updating custom plugins and themes based on an JSON REST API response from a custom update server. Ch

WP Forge 7 Oct 5, 2022
A custom update API for WordPress plugins and themes

A custom update API for WordPress plugins and themes. Intended to be used in conjunction with my plugin-update-checker library.

Yahnis Elsts 717 Dec 31, 2022
A PHP Class for creating Wordpress Custom Post Types easily

N.B I've released an updated version of the project to a new repository, PostTypes. WP Custom Post Type Class v1.4 A single class to help you build mo

Joe Grainger 412 Nov 25, 2022
A library to allow the use of PHP attributes for WordPress hooks

WordPress Hook Attributes This library should be considered experimental and not production ready. Installation composer require boxuk/wp-hook-attribu

Box UK 9 Nov 23, 2022
Use WordPress backend with Laravel or any PHP application

A collection of Model classes that allows you to get data directly from a WordPress database. Corcel is a collection of PHP classes built on top of El

Corcel PHP 3.9k Dec 29, 2022
Use WordPress backend with Laravel or any PHP application

A collection of Model classes that allows you to get data directly from a WordPress database. Corcel is a collection of PHP classes built on top of El

Corcel PHP 3.9k Jan 7, 2023
Style guide for writing consistent PHP for WordPress projects.

Inpsyde PHP Coding Standards PHP 7+ coding standards for Inpsyde WordPress projects. Installation The code styles are enforced via the popular php_cod

Inpsyde GmbH 77 Nov 14, 2022
A simple platform information plugin for WordPress. Shows you environment variables, PHP settings and more.

A simple platform information plugin for WordPress. Shows you environment variables, PHP settings and more.

New To Vaux 2 Sep 7, 2022