如何在发送电子邮件之前翻译wordpress联系表7消息

问题描述 投票:0回答:1

我正在尝试在发送电子邮件之前翻译 WordPress Contact Form 7 消息。我正在使用 https://google-translate1.p.rapidapi.com/language/translate/v2 上的 API,并为此创建了一个插件。然而,它并没有达到预期的效果。这是代码 到目前为止我已经尝试过了,但它的功能似乎有点问题您能推荐一个插件吗?

<?php
add_action("wpcf7_before_send_mail", "translate_message_before_send");

function translate_message_before_send($contact_form)
{
    // Get the submitted form data
    $submission = WPCF7_Submission::get_instance($contact_form);
    //     if (!$submission) {
    //         return;
    //     }

    // $posted_data = $submission->get_posted_data($contact_form);

    //      $name = $posted_data['your-name'];
    //         $message = $posted_data['your-message'];

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://google-translate1.p.rapidapi.com/language/translate/v2",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => "q=வணக்கம், உலகம்!&target=en",
        CURLOPT_HTTPHEADER => [
            "Accept-Encoding: application/gzip",
            "X-RapidAPI-Host: google-translate1.p.rapidapi.com",
            "X-RapidAPI-Key: X-RapidAPI-Key",
            "content-type: application/x-www-form-urlencoded",
        ],
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    error_log("curl_exec");

    $translated_message = json_decode($response, true);

    if (
        isset($translated_message["data"]["translations"][0]["translatedText"])
    ) {
        // Update the hidden field value with the translated message
        //  error_log('translations data');
        $contact_form->set_properties([
            "additional_settings" =>
                "your-translated-message: " .
                $translated_message["data"]["translations"][0][
                    "translatedText"
                ],
        ]);
    }
}

wordpress contact-form-7
1个回答
0
投票

您的函数调用联系表单提交的数据不正确。

$submission = WPCF7_Submission::get_instance($contact_form);

会抛出错误,因为不应将任何内容传递给该方法

get_instance()

所以你的简化代码应该是:

add_action( 'wpcf7_before_send_mail', 'translate_message_before_send', 10, 3 );

/**
 * Translate the submitted message before sending.
 *
 * @param object $contact_form The Contact Form object.
 * @param bool   $abort        Whether to abort sending the message.
 * @param object $submission   The Form Submission object.
 */
function translate_message_before_send( $contact_form, $abort, $submission ) {
    // Get the submitted form data.
    $posted_data = $submission->get_posted_data();

如果添加包含的参数,$submission 对象已传递给函数。

此外,如果您希望它更“正确”,您应该重写

$curl
以使用
wp_remote_post

© www.soinside.com 2019 - 2024. All rights reserved.