您不必编写新插件。您可以将代码添加到主题的functions.php
文件,或创建child theme.
要以JSON格式包装数据,可以使用json_encode
作用发布后挂接到帖子中,并发送数据。在下面的函数中,我将把帖子的标题、摘录和特色图片URL发送到端点。
add_action(\'publish_post\', \'call_the_endpoint\',10,2);
function call_the_endpoint($post_id, $post){
// Define an empty array
$data = array();
// Store the title into the array
$data[\'title\'] = get_the_title();
// If there is a post thumbnail, get the link
if (has_post_thumbnail()) {
$data[\'thumbnail\'] = get_the_post_thumbnail_url( get_the_ID(),\'thumbnail\' );
}
// Get the excerpt and save it into the array
$data[\'excerpt\'] = get_the_excerpt();
// Encode the data to be sent
$json_data = json_encode($data);
// Initiate the cURL
$url = curl_init(\'YOUR API URL HERE\');
curl_setopt($url, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($url, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($url, CURLOPT_RETURNTRANSFER, true);
curl_setopt($url, CURLOPT_HTTPHEADER, array(
\'Content-Type: application/json\',
\'Content-Length: \' . strlen($json_data))
);
// The results of our request, to use later if we want.
$result = curl_exec($url);
}
如果您能够提供有关API以及如何与API交互的更多信息,那么就有可能写出准确的答案。然而,这是一个简单的示例,让您知道如何使用
publish_post
钩住你想要的东西。