php - WooCommerce 通过 AJAX 触发自定义电子邮件

标签 php oop wordpress woocommerce

您好,感谢您的光临。 我目前正在为 wordpress 编写一个插件。我需要某个页面内的按钮,触发电子邮件通知。我认为使用 woocommerce 电子邮件功能会很好,因为它是客户电子邮件,我也想使用 woocommerce-email-templates。

在我的插件中我包含了我的类扩展

function add_wc_custom_email( $email_classes ) {
    require( 'includes/class-wc-custom-email.php' );
    $email_classes['WC_Custom_Email'] = new WC_Custom_Email();

    return $email_classes;
}
add_filter( 'woocommerce_email_classes', 'add_wc_custom_email' );
//if i write a print_r(something) inside this function, just to alert if this filters hits, i don't see a result, so i think the error is here.. the filter gets hit under woocommerce->settings->emails but not, if you simply load a page in the backend 

在文件 class-wc-custom-email.php 中我有我的类扩展

class WC_Custom_Email extends WC_Email {
    public function __construct() {
        …
    }
    public function mail( $var1, $var2, $var3 ) {
        …
    }
}

我的ajax是这样的

( function( $ ) {
    $('#button1').on( "click", function() {
        $.post(
            ajaxurl,
            {
                'action' : 'jnz_email_custom',
                'page_id': '<?php the_ID(); ?>',
            },
            function ( response ) {
                console.log( "triggered", response )
            }
        );
    });
})(jQuery);

ajax 处理程序看起来像这样

add_action('wp_ajax_jnz_email_custom', 'jnz_email_custom');
function jnz_email_custom() {
    $message = email_custom( $_POST['page_id'] );
    $response = array(
        'what'   => 'email_custom_triggered',
        'action' => 'email custom triggered',
        'id'     => $_POST['page_id'],
        'data'   => $message,
    );
    $xmlResponse = new WP_Ajax_Response( $response );
    $xmlResponse->send();
}

我用ajax触发的函数

function email_custom( $page_id = 2728 ) {
    $field = get_field( 'something', $page_id )[0];
    //get_field() is a function by plugin 'Advanced Custom Fields' and works fine

    function somethingSomething( $field ) {
        …
        return $results;
    }

    foreach ( $results as $result ) :
        $email = new WC_Custom_Email();
        $email->mail( $result['details']['name'], $result['details']['email'], $result['something'] );
    endforeach;

    return json_encode( $results, JSON_UNESCAPED_UNICODE );
    //this is the $xmlResponse i get from the ajax call and looks fine (but only works, if i uncomment the 'new WC_Custom_Email()' stuff. otherwise i see the "Fatal Error" thingy)
}

响应是: fatal error :在...中找不到类“WC_Custom_Email”

所有功能都工作正常,如果我返回 $results,我会看到所有我想要的并且没有错误。

相同的是,当我将其更改为 new WC_Email() 时。所以我的猜测是,woocommerce 功能没有加载到我的 admin->edit_page_xy 屏幕中。所以最大的问题是:我如何将 woocommerce 功能(或仅电子邮件功能)加载到我的插件中..??

希望这有点清楚并且有任何意义。我对 PHP 知之甚少,对 oop 完全陌生。

最佳答案

好吧,这有点像野兽。

我编写了一个具有以下结构的演示插件:

kia-ajax-email.php
- includes
  -- class-wc-test-ajax-email.php
-- js
   -- script.js
-- templates
   -- emails
      -- test.php
      -- plain
         -- test.php

主要插件文件kia-ajax-email.php

此文件负责将脚本排入队列、添加您的自定义电子邮件类、在单个产品页面上创建按钮以及将操作注册为触发 WooCommerce 电子邮件的操作:

<?php
/**
 * Plugin Name: Test Ajax Email
 * Plugin URI: http://stackoverflow.com/q/35018177/383847
 * Description: Demo plugin for sending email via ajax
 * Author: helgatheviking
 * Author URI: http://www.kathyisawesome.com
 * Version: 0.1
 *
 * License: GNU General Public License v3.0
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 *
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly


/**
 *  get plugin path
 *
 * @since 0.1
 */
function kia_ajax_email_plugin_path(){
    return untrailingslashit( plugin_dir_path( __FILE__ ) ); 
}

/**
 *  Add a custom email to the list of emails WooCommerce should load
 *
 * @since 0.1
 * @param array $email_classes available email classes
 * @return array filtered available email classes
 */
function kia_add_custom_email( $email_classes ) {

    // include our custom email class
    require_once( 'includes/class-wc-test-ajax-email.php' );

    // add the email class to the list of email classes that WooCommerce loads
    $email_classes['WC_Test_Ajax_Email'] = new WC_Test_Ajax_Email();

    return $email_classes;

}
add_filter( 'woocommerce_email_classes', 'kia_add_custom_email' );


/**
 *  Enqueue the scripts with apprpriate vars
 *
 * @since 0.1
 */
function kia_ajax_email_js(){
    wp_enqueue_script( 'kia_ajax_email', plugins_url( 'js/script.js', __FILE__ ), array('jquery'), '1.0.0', true );
    wp_localize_script( 'kia_ajax_email', 'kia_ajax_email', array( 
                'ajax_url'                  => WC()->ajax_url(),
                'wc_ajax_url'               => WC_AJAX::get_endpoint( "test_email" ) ) );
}
add_action( 'wp_enqueue_scripts', 'kia_ajax_email_js', 20 );


/**
 *  AJAX callback
 *
 * @since 0.1
 */
function kia_ajax_email_callback() {
    $mailer = WC()->mailer();

    do_action( 'kia_trigger_ajax_email' );

    die('ajax finished'); // this is required to terminate immediately and return a proper response
}
add_action( 'wc_ajax_test_email', 'kia_ajax_email_callback' );


/**
 *  Register action as one that sends emails
 *
 * @since 0.1
 */
function kia_ajax_email_action( $actions ){
    $actions[] = 'kia_trigger_ajax_email';
    return $actions;
}
add_action( 'woocommerce_email_actions', 'kia_ajax_email_action' );


/**
 *  Add a dummy button to product page
 *
 * @since 0.1
 */
function kia_ajax_email_button(){
    echo '<button class="email-trigger">' . __( 'Email Trigger', 'kia-ajax-email' ). '</button>';
}
add_action('woocommerce_before_single_product_summary', 'kia_ajax_email_button');

电子邮件类 includes/class-wc-test-ajax-email.php

<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * A custom Expedited Order WooCommerce Email class
 *
 * @since 0.1
 * @extends \WC_Email
 */
class WC_Test_Ajax_Email extends WC_Email {


    /**
     * Set email defaults
     *
     * @since 0.1
     */
    public function __construct() {

        // set ID, this simply needs to be a unique name
        $this->id = 'wc_text_ajax_email';

        // this is the title in WooCommerce Email settings
        $this->title = 'Test Ajax';

        // this is the description in WooCommerce email settings
        $this->description = 'Text emails are sent when ajax button is clicked';

        // these are the default heading and subject lines that can be overridden using the settings
        $this->heading = 'Test Ajax';
        $this->subject = 'Test Ajax';

        // these define the locations of the templates that this email should use, we'll just use the new order template since this email is similar
        $this->template_html  = 'emails/test.php';
        $this->template_plain = 'emails/plain/test.php';

        // Trigger on new paid orders
        add_action( 'kia_trigger_ajax_email', array( $this, 'trigger' ) );

        // Call parent constructor to load any other defaults not explicity defined here
        parent::__construct();

        // this sets the recipient to the settings defined below in init_form_fields()
        $this->recipient = $this->get_option( 'recipient' );

        // if none was entered, just use the WP admin email as a fallback
        if ( ! $this->recipient )
            $this->recipient = get_option( 'admin_email' );
    }


    /**
     * Determine if the email should actually be sent and setup email merge variables
     *
     * @since 0.1
     * @param int $order_id
     */
    public function trigger() {

        if ( ! $this->is_enabled() || ! $this->get_recipient() )
            return;

        // woohoo, send the email!
        $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
    }


    /**
     * get_content_html function.
     *
     * @since 0.1
     * @return string
     */
    public function get_content_html() {
        return wc_get_template_html( $this->template_html, array(
            'email_heading' => $this->get_heading(),
            'sent_to_admin' => false,
            'plain_text'    => false,
            'email'         => $this
        ),
        '',
        kia_ajax_email_plugin_path() . "/templates/" );
    }


    /**
     * get_content_plain function.
     *
     * @since 0.1
     * @return string
     */
    public function get_content_plain() {
        return wc_get_template_html( $this->template_plain, array(
            'email_heading' => $this->get_heading(),
            'sent_to_admin' => false,
            'plain_text'    => false,
            'email'         => $this
        ),
        '',
        kia_ajax_email_plugin_path() . "/templates/" );
    }


    /**
     * Initialize Settings Form Fields
     *
     * @since 2.0
     */
    public function init_form_fields() {

        $this->form_fields = array(
            'enabled'    => array(
                'title'   => 'Enable/Disable',
                'type'    => 'checkbox',
                'label'   => 'Enable this email notification',
                'default' => 'yes'
            ),
            'recipient'  => array(
                'title'       => 'Recipient(s)',
                'type'        => 'text',
                'description' => sprintf( 'Enter recipients (comma separated) for this email. Defaults to <code>%s</code>.', esc_attr( get_option( 'admin_email' ) ) ),
                'placeholder' => '',
                'default'     => ''
            ),
            'subject'    => array(
                'title'       => 'Subject',
                'type'        => 'text',
                'description' => sprintf( 'This controls the email subject line. Leave blank to use the default subject: <code>%s</code>.', $this->subject ),
                'placeholder' => '',
                'default'     => ''
            ),
            'heading'    => array(
                'title'       => 'Email Heading',
                'type'        => 'text',
                'description' => sprintf( __( 'This controls the main heading contained within the email notification. Leave blank to use the default heading: <code>%s</code>.' ), $this->heading ),
                'placeholder' => '',
                'default'     => ''
            ),
            'email_type' => array(
                'title'       => 'Email type',
                'type'        => 'select',
                'description' => 'Choose which format of email to send.',
                'default'     => 'html',
                'class'       => 'email_type',
                'options'     => array(
                    'plain'     => __( 'Plain text', 'woocommerce' ),
                    'html'      => __( 'HTML', 'woocommerce' ),
                    'multipart' => __( 'Multipart', 'woocommerce' ),
                )
            )
        );
    }


} // end \WC_Test_Ajax_Email class

脚本js/script.js

jQuery(document).ready(function($) {

  $(".email-trigger").on("click", function(e) {

    e.preventDefault();

    $.ajax({
        url: kia_ajax_email.wc_ajax_url.toString(),
        type: 'POST',
        data: {
          'whatever': 1234
        },
      })
      .done(function(data) {
        if (console && console.log) {
          console.log(data);
        }
      });
  });

});

电子邮件模板。首先是 templates/emails/test.phptemplates/emails/plain/test.php

<?php
/**
 * Test email
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/test.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
 * will need to copy the new files to your theme to maintain compatibility. We try to do this.
 * as little as possible, but it does happen. When this occurs the version of the template file will.
 * be bumped and the readme will list any important changes.
 *
 * @see         http://docs.woothemes.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates/Emails
 * @version     2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * @hooked WC_Emails::email_header() Output the email header
 */
do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<p><?php _e( 'A test email is being sent', 'kia-ajax-email' ); ?></p>


<?php
/**
 * @hooked WC_Emails::email_footer() Output the email footer
 */
do_action( 'woocommerce_email_footer', $email );

templates/emails/plain/test.php

<?php
/**
 * Test email
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/plain/test.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
 * will need to copy the new files to your theme to maintain compatibility. We try to do this.
 * as little as possible, but it does happen. When this occurs the version of the template file will.
 * be bumped and the readme will list any important changes.
 *
 * @see         http://docs.woothemes.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates/Emails
 * @version     2.5.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


echo "= " . $email_heading . " =\n\n";

echo "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";


_e( 'A test email is being sent', 'kia-ajax-email' );

echo "\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n\n";

echo apply_filters( 'woocommerce_email_footer_text', get_option( 'woocommerce_email_footer_text' ) );

展望 future

这会在单击按钮时发送一封电子邮件。您将需要修改该按钮的位置,并且因为它有点慢(或者在我的本地设置中看起来很慢)我肯定会推荐某种微调器/通知来指示该操作正在发生。您还需要自定义通过 ajax 发送的数据以及这些数据如何在模板中结束。这只是一个概念证明。

关于php - WooCommerce 通过 AJAX 触发自定义电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35018177/

相关文章:

php - 使用任何 PHP 循环从数据库表创建多个 html 表

php - 如何更改 WordPress 网站中的 WooCommerce 产品图片大小?

php 使用 switch 不间断;

javascript - ajax调用成功后如何触发动画模态窗口?

涉及函数、递归和类的 Python 练习

c++ - 在派生类中覆盖/重新实现枚举

c# - 这是构造函数声明吗?

php - 如何在外部网站上提供 wordpress 帖子

php - 我将使用哪些 PHP 函数结合 AJAX/无限滚动来加载 WordPress 网站的页面?

javascript - 如何通过javascript在dropzone上传帖子中发送csrf token ?