WordPress and CRM systems

Hello everyone! I won't waste time on unnecessary introductory words, but will get straight to the point. In this short article, I will share my experience of integrating WordPress with CRM systems.

Often, clients want the data collected from contact forms to be automatically sent to their CRM. So how do you implement this in WordPress? Let's find out.

Personally, I have come across three types of forms that are used in WordPress: forms created with a plugin Contact Form 7forms developed in Elementorand self-written forms that work on AJAX. And one more thing In rare cases, there is interaction with WooCommerce.

Contact Form 7

<?php
add_action('wpcf7_before_send_mail', 'custom_wpcf7_before_send_mail');

function custom_wpcf7_before_send_mail($contact_form) {
    // Получаем данные формы
    $submission = WPCF7_Submission::get_instance();
    
    if ($submission) {
        $data = $submission->get_posted_data();  // Получаем данные формы

        // Доступ к данным формы
        $name = isset($data['your-name']) ? $data['your-name'] : '';  // Замените 'your-name' на имя вашего поля
        $email = isset($data['your-email']) ? $data['your-email'] : ''; // Замените 'your-email' на имя вашего поля

        // Отправка данных на внешний сервис
        $response = wp_remote_post('https://example.com/api', array(
            'method'    => 'POST',
            'body'      => json_encode(array(
                'name' => $name,
                'email' => $email,
            )),
            'headers'   => array(
                'Content-Type' => 'application/json',
            ),
        ));

        // Проверка ответа
        if (is_wp_error($response)) {
            // Обработка ошибки
            error_log('Ошибка отправки данных на внешний сервис: ' . $response->get_error_message());
        } else {
            // Обработка успешного ответа
            error_log('Данные успешно отправлены на внешний сервис');
        }
    }
}

It's simple here. We intercept POST data via hook wpcf7_before_send_mail.

We can analyze what exactly is being sent in the form and substitute our own values.

Elementor

<?php
add_action('elementor_pro/forms/new_record', function($record, $handler) {
    // Получаем данные формы
    $raw_data = $record->get( 'fields' );

    // Форматируем данные для отправки
    $data_to_send = [];
    foreach ( $raw_data as $key => $value ) {
        // Здесь вы можете добавить фильтрацию или проверку
        $data_to_send[$key] = sanitize_text_field($value);
    }

    // Теперь отправьте данные на ваш сервис статистики
    $response = wp_remote_post('https://your-stats-service.com/api/endpoint', [
        'method'    => 'POST',
        'body'      => json_encode($data_to_send),
        'headers'   => [
            'Content-Type' => 'application/json',
        ],
    ]);

    // Обработка ответа
    if ( is_wp_error( $response ) ) {
        // Логирование ошибки или другие действия
    } else {
        // Данные успешно отправлены
    }

    // Сохраняем данные в сессии или делаем другие операции, если нужно

}, 10, 2 );

It's about the same here as in the first option.

Elementor provides a hook elementor_pro/forms/new_recordwhich allows you to intercept form data immediately after it is submitted, but before it is processed. You can use this hook in your functions.php your topic.

WordPress and AJAX

<?php
// Обработка AJAX-запроса
add_action('wp_ajax_my_form_submission', 'handle_my_form_submission');
add_action('wp_ajax_nopriv_my_form_submission', 'handle_my_form_submission');

function handle_my_form_submission() {
    // Получаем данные из запроса
    $name = isset($_POST['name']) ? sanitize_text_field($_POST['name']) : null;
    $email = isset($_POST['email']) ? sanitize_email($_POST['email']) : null;
    
    // Здесь вы можете добавить код для обработки данных, например, отправка в CRM

    // Возвращаем ответ
    wp_send_json_success(array('message' => 'Данные успешно отправлены!'));
}

Here I have shown a typical example of use AJAX V WP. Something similar should be found in the project code. You can search by keyword 'wp_ajax_'. And depending on the situation, use the code that will be responsible for sending data V CRM.

WooCommerce

Sometimes situations arise when it is necessary to send data immediately after completing an order.

<?php
add_action( 'woocommerce_thankyou', 'custom_after_order_received', 10, 1 );
function custom_after_order_received( $order_id ) {
    // Получение данных заказа
    $order = wc_get_order( $order_id );

    //при желании можно получить и передать список купленых товаров!
    //$products = get_product_list_by_string( $order_id );

    $name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
    $phone = $order->get_billing_phone();
    $email = $order->get_billing_email();
    
    // Отправка данных на внешний сервис
        $response = wp_remote_post('https://example.com/api', array(
            'method'    => 'POST',
            'body'      => json_encode(array(
                'name' => $name,
                'phone' => $phone
                'email' => $email,
            )),
            'headers'   => array(
                'Content-Type' => 'application/json',
            ),
        ));

        // Проверка ответа
        if (is_wp_error($response)) {
            // Обработка ошибки
            error_log('Ошибка отправки данных на внешний сервис: ' . $response->get_error_message());
        } else {
            // Обработка успешного ответа
            error_log('Данные успешно отправлены на внешний сервис');
        }
}

Hook woocommerce_thankyou is part of the hook system in WooCommerce and allows developers to perform specific actions when a user completes a purchase and sees a Thank You page after placing an order.

If you have any questions or your own experience in this matter, please share in the comments! Thank you for your attention!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *