Die() предотвращает отправку почты wp_mail

#wordpress #email #woocommerce

#wordpress #Адрес электронной почты #woocommerce

Вопрос:

У меня есть простая регистрационная форма в woocommerce, которая должна отправлять электронное письмо зарегистрированному пользователю, но этого не происходит. Вот код, который отправляет форму:

 $(".submitbtn").click(function() {
    $('#result').html('<img src="' ajax_script.loading_img '" class="loader" />').fadeIn();
    var input_data = $('#wp_signup_form').serialize();
    input_data  = 'amp;action=et_register_action';
    $.ajax({
        type: "GET",
        dataType: "JSON",
        url: ajax_script.ajax_url,
        data: input_data,
        success: function(response){
            response = JSON.parse(response);
            console.log(response);
            $('.loader').remove();
            if(response.status == 'error') {
                var msgHtml = '<span class="error">'   response.msg   '</span>';
                $('<div>').html(msgHtml).appendTo('div#result').hide().fadeIn('slow');

            } else {
                var msgHtml = '<span class="success">'   response.msg   '</span>';
                $('<div>').html(msgHtml).appendTo('div#result').hide().fadeIn('slow');
                $('#wp_signup_form').find("input[type=text], input[type=password], textarea").val("");
            }
        }
    });
    return false;
});
  

И это и извлечение обработчика регистрации:

 if ( is_wp_error($status) ) {
    $return['status'] = 'error';
    $return['msg'] = __( "Username already exists. Please try another one.", ETHEME_DOMAIN );
    echo json_encode($return);
}
else {
    $from = get_bloginfo('name');
    $from_email = get_bloginfo('admin_email');
    $headers = 'From: ' . $from . " <" . $from_email . ">rn";
    $headers .= "MIME-Version: 1.0rn";
    $headers .= "Content-Type: text/html; charset=UTF-8rn";
    $subject = __("Registration successful", ETHEME_DOMAIN);
    $message = et_registration_email($username);
    wp_mail($email, $subject, $message, $headers);
    $return['status'] = 'success';
    $return['msg'] = __("Please check your email for login details.", ETHEME_DOMAIN);
    echo json_encode($return);
}
die();
  

Этот die() сводит меня с ума!!

  • Если я сохраню его, страница загрузится идеально, пользователь будет добавлен в список, но письма не приходят.
  • Если я удалю его, пользователь будет добавлен, почта приходит правильно, но к строке json добавляется ‘0’, поэтому я не могу ее прочитать.

Я обнаружил, что wp_ajax.php заканчивайте на die(0); , добавляя таким образом ‘0’ в конце любого вывода ajax. Нужно исправить это, введя die() собственный код, но как? Я также пытался использовать usleep(800000) , но все еще не работает.

Почта работает корректно, поэтому я не хотел бы устанавливать какой-либо сторонний плагин. Любая помощь приветствуется.

РЕДАКТИРОВАТЬ: через несколько часов на почтовый адрес отправителя приходит сообщение:

 host outbound.mailspamprotection.com [96.127.176.250]
SMTP error from remote mail server after end of data:
550 A URL in this email (8theme . com) is listed on https://spamrl.com/. Please resolve and retry
  

Как возможно, что это письмо не распознается как спам, если я удаляю die() ?

Ответ №1:

Попробуйте wp_die() вместо этого. Возможно, необходимо запустить какие-то другие хуки или обработчики, и использование wp-оболочки die позволяет им это сделать.

Запись WP Codex: https://codex.wordpress.org/Function_Reference/wp_die

Выдержка из wp-includes/functions.php. :

 /**
 * Kill WordPress execution and display HTML message with error message.
 *
 * This function complements the `die()` PHP function. The difference is that
 * HTML will be displayed to the user. It is recommended to use this function
 * only when the execution should not continue any further. It is not recommended
 * to call this function very often, and try to handle as many errors as possible
 * silently or more gracefully.
 *
 * As a shorthand, the desired HTTP response code may be passed as an integer to
 * the `$title` parameter (the default title would apply) or the `$args` parameter.
 *
 * @since 2.0.4
 * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
 *              an integer to be used as the response code.
 *
 * @param string|WP_Error  $message Optional. Error message. If this is a {@see WP_Error} object,
 *                                  the error's messages are used. Default empty.
 * @param string|int       $title   Optional. Error title. If `$message` is a `WP_Error` object,
 *                                  error data with the key 'title' may be used to specify the title.
 *                                  If `$title` is an integer, then it is treated as the response
 *                                  code. Default empty.
 * @param string|array|int $args {
 *     Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
 *     as the response code. Default empty array.
 *
 *     @type int    $response       The HTTP response code. Default 500.
 *     @type bool   $back_link      Whether to include a link to go back. Default false.
 *     @type string $text_direction The text direction. This is only useful internally, when WordPress
 *                                  is still loading and the site's locale is not set up yet. Accepts 'rtl'.
 *                                  Default is the value of {@see is_rtl()}.
 * }
 */
function wp_die( $message = '', $title = '', $args = array() ) {

        if ( is_int( $args ) ) {
                $args = array( 'response' => $args );
        } elseif ( is_int( $title ) ) {
                $args  = array( 'response' => $title );
                $title = '';
        }

        if ( defined( 'DOING_AJAX' ) amp;amp; DOING_AJAX ) {
                /**
                 * Filter callback for killing WordPress execution for AJAX requests.
                 *
                 * @since 3.4.0
                 *
                 * @param callable $function Callback function name.
                 */
                $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
        } elseif ( defined( 'XMLRPC_REQUEST' ) amp;amp; XMLRPC_REQUEST ) {
                /**
                 * Filter callback for killing WordPress execution for XML-RPC requests.
                 *
                 * @since 3.4.0
                 *
                 * @param callable $function Callback function name.
                 */
                $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
        } else {
                /**
                 * Filter callback for killing WordPress execution for all non-AJAX, non-XML-RPC requests.
                 *
                 * @since 3.0.0
                 *
                 * @param callable $function Callback function name.
                 */
                $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
        }

        call_user_func( $function, $message, $title, $args );
}
  

Ответ №2:

попробуйте exit; вместо этого. или wp_die();