Как добавить Yandex SmartCaptcha в форму контактов
Чтобы защитить контактную форму на вашем сайте с помощью яндекс капчи, нужно сначала создать и настроить её в консоли yandex.cloud, чтобы получить ключи

Затем нужно добавить такой код в плагин ProFunctions и вставить ключи капчи вместо строк Ключ_клиента и Ключ_сервера
class CustomContactFormYandexSmartCaptcha {
protected $site_key;
protected $secret_key;
/**
* @param string $site_key
* @param string $secret_key
*/
public function __construct( $site_key, $secret_key ) {
$this->site_key = $site_key;
$this->secret_key = $secret_key;
}
public function init() {
add_action( 'wp_enqueue_scripts', [ $this, '_enqueue_scripts' ], 11 );
add_filter( 'wpshop_text_before_submit', [ $this, '_get_captcha_html' ] );
add_filter( 'wpshop_contact_form_errors', [ $this, '_get_validation_errors' ] );
}
public function _enqueue_scripts() {
wp_enqueue_script(
'yandex-smartcaptcha',
'https://smartcaptcha.cloud.yandex.ru/captcha.js',
[],
null,
true
);
$css = <<<'CSS'
.contact-form--captcha .smart-captcha {
max-width: 100%;
}
@media (min-width: 768px) {
.contact-form--captcha .smart-captcha {
max-width: 60%
}
}
CSS;
wp_add_inline_style('reboot-style', $css );
}
public function _get_captcha_html() {
$site_key = esc_attr( $this->site_key );
return <<<HTML
<div class="contact-form__field contact-form--captcha">
<div class="smart-captcha"
data-sitekey="{$site_key}">
</div>
</div>
HTML;
}
public function _get_validation_errors( $errors ) {
$token = $_POST['smart-token'] ?? '';
if ( empty( $token ) ) {
$errors[] = 'Подтвердите, что вы не робот.';
} else if ( ! $this->validate( $token ) ) {
$errors[] = 'Не удалось пройти проверку на робота';
}
return $errors;
}
protected function validate( $token ) {
$response = wp_remote_post(
'https://smartcaptcha.yandexcloud.net/validate',
[
'body' => [
'secret' => $this->secret_key,
'token' => $token,
'ip' => $_SERVER['REMOTE_ADDR'],
],
]
);
$data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( empty( $data['status'] ) || $data['status'] !== 'ok' ) {
return false;
}
return true;
}
}
( new CustomContactFormYandexSmartCaptcha(
'Ключ_клиента',
'Ключ_сервера'
) )->init();
Вам помог ответ?