注:该WP REST API 可能是更好的选择
客户端
假设我们使用内置
WP_HTTP_IXR_CLIENT
(例如,请参见我以前的
answer):
include_once( ABSPATH . WPINC . \'/class-IXR.php\' );
include_once( ABSPATH . WPINC . \'/class-wp-http-ixr-client.php\' );
$client = new WP_HTTP_IXR_CLIENT( \'https://example.tld/xmlrpc.php\' );
$result = $client->query(
\'wp.newPost\',
[
$blog_id = 0,
$user = "user", // <-- Edit this
$password = "password", // <-- Edit this
[
\'post_status\' => \'draft\', // Here we use \'draft\' while testing
\'post_title\' => \'xml-rpc testing - random \' . rand( 0, 999 ),
\'post_content\' => \'Hello xml-rpc!\' ,
]
]
);
我们无法从
$result
, 正如人们所料。
请注意,对于成功的请求WP_HTTP_IXR_Client::query
仅方法返回true
, 其他的false
.
wp.newPost
响应成功wp.newPost
回答如下
<?xml version="1.0"?>
<methodCall>
<methodName>wp.newPost</methodName>
<params>
<param><value><array><data>
<value><int>0</int></value>
<value><string>user</string></value>
<value><string>password</string></value>
<value><struct>
<member><name>post_status</name><value><string>draft</string></value></member>
<member><name>post_title</name><value><string>xml-rpc testing - random 471</string></value></member>
<member><name>post_content</name><value><string>hello xml-rpc!</string></value></member>
</struct></value>
</data></array></value></param>
</params></methodCall>
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<params>
<param>
<value>
<string>123</string>
</value>
</param>
</params>
</methodResponse>
在那里我们展示了它
$client->debug = true;
但请注意,这是在打开时显示用户密码!
以下是客户端处理调试的方式:
if ( $this->debug ) {
echo \'<pre class="ixr_response">\'
. htmlspecialchars( wp_remote_retrieve_body( $response ) )
. "\\n</pre>\\n\\n";
}
消息这是如何构造消息属性的:
$this->message = new IXR_Message( wp_remote_retrieve_body( $response ) );
然后我们可以看到
WP_HTTP_IXR_CLIENT::query
尝试分析它:
if ( ! $this->message->parse() ) {
// XML error
$this->error = new IXR_Error(-32700, \'parse error. not well formed\');
return false;
}
它还检查故障消息类型:
// Is the message a fault?
if ( $this->message->messageType == \'fault\' ) {
$this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
return false;
}
如果成功,则返回true:
// Message must be OK
return true;
相应的
IXR_Message
对象看起来像
IXR_Message object (
[message] =>
[messageType] => methodResponse
[faultCode] =>
[faultString] =>
[methodName] =>
[params] => Array
(
[0] => 123
)
[_arraystructs] => Array
(
)
[_arraystructstypes] => Array
(
)
[_currentStructName] => Array
(
)
[_param] =>
[_value] =>
[_currentTag] =>
[_currentTagContents] =>
[_parser] => Resource id #155
[currentTag] => string
)
在哪里
123
是新的帖子ID。
示例
下面是一个示例,我们可以通过自定义方法获得新的帖子ID:
$post_id = 0;
if( ! is_a( $client->error, \'\\IXR_Error\' ) )
return $post_id;
if( ! is_a( $client->message, \'\\IXR_Message\' ) )
return $post_id;
if( \'methodResponse\' !== $client->message->messageType )
return $post_id;
if( ! isset( $client->message->params[0] ) )
return $post_id;
$post_id = $client->message->params[0];
return $post_id;
希望有帮助。