在多站点环境中,获取变量形式的子域值

时间:2021-08-14 作者:Alvaro Gilabert

我正在尝试设置一个多站点,每次添加新站点时,都会在Cloudflare中添加一个DNS记录。到目前为止,代码仍在运行,但我在尝试将子域值解析到变量上时遇到了问题。

这是迄今为止的代码:

function create_cloudflare_dns_record() {

//$current_site = \'\'.$get_blog_details->siteurl.\'\';
//$current_site = \'\'.$substr( $current_site, -8).\'\';
//$current_site = \'\'.explode(\'.\', $current_site).\'\';


/* Cloudflare.com | APİv4 | Api Ayarları */
$apikey     = \'778***************************c37\'; // Cloudflare Global API
$email      = \'al******@***********.com\'; // Cloudflare Email Adress
$domain     = \'mer*****.com\';  // zone_name // Cloudflare Domain Name
$zoneid     = \'ecc**********************1e1\'; // zone_id // Cloudflare Domain Zone ID
//$current_site   = \'\'.$get_sites->path.\'\';
$current_site = explode(\'.\', $_SERVER[\'HTTP_HOST\']);


// $_SERVER[\'HTTP_HOST\']

// A-record oluşturur DNS sistemi için.
$ch = curl_init("https://api.cloudflare.com/client/v4/zones/".$zoneid."/dns_records");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
\'X-Auth-Email: \'.$email.\'\',
\'X-Auth-Key: \'.$apikey.\'\',
\'Cache-Control: no-cache\',
// \'Content-Type: multipart/form-data; charset=utf-8\',
\'Content-Type:application/json\',
\'purge_everything: true\'

));

// -d curl parametresi.
$data = array(

    \'type\' => \'CNAME\',
    \'name\' => \'\'.$current_site.\'\',
    \'content\' => \'mer***.com\',
    \'zone_name\' => \'\'.$domain.\'\',
    \'zone_id\' => \'\'.$zoneid.\'\',
    \'proxied\' => true,
    \'ttl\' => \'120\'
);

$data_string = json_encode($data);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data_string));

$sonuc = curl_exec($ch);

/*
    //print_r($sonuc);
*/

curl_close($ch);



}


add_action( \'wp_insert_site\', \'create_cloudflare_dns_record\' );
在函数的begining处对$current\\u站点进行的三次不同尝试都没有产生任何结果。

如果手动替换$current\\u site的值,则代码正常工作。

非常感谢您的帮助。

1 个回复
最合适的回答,由SO网友:Mohammad Qasim 整理而成

wp_insert_site 接收WP\\U Site对象,该对象包含有关当前站点的详细信息。https://developer.wordpress.org/reference/hooks/wp_insert_site/

将站点插入数据库后,将触发do\\u操作(“wp\\u insert\\u site”,wp\\u site$new\\u site)。

https://developer.wordpress.org/reference/classes/wp_site/

WP_Site Object (
    [blog_id] => 2
    [domain] => localhost
    [path] => /m2/sagres/
    [site_id] => 1
    [registered] => 2018-03-23 13:49:37
    [last_updated] => 2019-03-05 15:52:10
    [public] => 0
    [archived] => 0
    [mature] => 0
    [spam] => 0
    [deleted] => 0
    [lang_id] => 0 
)
所以总结一下,您可以更改函数定义以接受参数。

function create_cloudflare_dns_record(WP_Site $new_site) {
和使用$new_site->domain$new_site->path 获取所插入站点的详细信息