纠正我,如果我错了这里,但你现在有两个WordPress的网站。一种是使用api的插件myCRED。你想从另一个wordpress网站使用该api来显示信息。
您应该处理在客户端模板。我已经包含了一个示例,它列出了一个脚本,其中包含一个可以与wordpress后端进行通信的nonce和ajax url。
使用wp_ajax,您可以创建一个从myCRED API返回的数据,然后返回数据返回给谁要求其客户端的功能。
的模板应该如何处理,我留给你的,因为我不能确定这里的最终目标客户端。
这个例子也可以变成一个非常简单的插件,但为了简洁的缘故我已经证明只是包括这在你的functions.php文件
WordPress的排队脚本 https://developer.wordpress.org/reference/functions/wp_enqueue_script/
// functions.php
function my_cred_script() {
wp_register_script(
'cred-script',
get_template_directory_uri() . '/path/to/js/file.js',
array('jquery'),
null,
true
);
wp_enqueue_script('cred-script');
wp_localize_script('cred-script', 'ajax_object', array(
'cred_nonce' => wp_create_nonce('cred_nonce'),
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
的WordPress阿贾克斯参考 https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
// functions.php
function get_my_cred_data() {
if(!isset($_POST['cred_nonce']) ||
!wp_verify_nonce($_POST['cred_nonce'], 'cred_nonce')) {
die();
}
$secret_key = 'mysecretkey';
$remote_url = 'http://siteb.com/api/';
$action = 'GET';
$account = '[email protected]';
$point_type = 'my_custom_type';
$host = get_bloginfo('url');
$token = md5($host . $action . $secret_key);
$request = array(
'method' => 'POST',
'body' => array(
'action' => $action,
'account' => $account,
'type' => $point_type,
'token' => $token,
'host' => $host
)
);
$response = wp_remote_post($remote_url, $request);
echo $response;
die();
}
add_action('wp_ajax_cred_data', 'get_my_cred_data');
add_action('wp_ajax_nopriv_cred_data', 'get_my_cred_data');
在你一些javscript文件r从上面入选的主题。我们现在可以调用我们在客户端的wordpress中创建的操作('cred_data')。我们应该找回一些json,然后我们可以模板化它。
function getCREDData() {
var options = {
action: 'cred_data',
cred_nonce: ajax_object.cred_nonce
};
$.post(ajax_object.ajax_url, options)
.then(function(response) {
// handle response
})
.catch(function(err) {
// handle err
});
}
也可以使用get_current_user();在$ account变量内添加当前用户的电子邮件? – WordPressFreddie
另外我想指出,我知道密钥和url需要更改为我的API,但我不想公开发布它们。 – WordPressFreddie
这里是什么特定于wordpress插件为什么你不能从你的其他应用程序调用这个? – Ace