点击按钮加载php文件


php file to load on click button

我正在加载personalizetest.php(它有发送电子邮件的swiftmailer代码)点击事件。当我点击带有jquery代码的html文件中的按钮加载它时,它就工作了,并发送了一封电子邮件。但当我在WordPress的php文件中添加相同的代码,并点击按钮时,控制台上会显示"操作执行成功",但我没有收到任何电子邮件。

我搜索了一下,发现我必须在function.php中添加以下代码才能在Wordpress上执行文件,我确实这样做了,但现在它在每次刷新页面时都会发送电子邮件。要么我打开网站,要么从一个页面转到另一个页面,而不是点击按钮。简而言之,当我用class=button:点击按钮时,我正在加载这个personalizetest.php文件

函数.php

<?php
function enqueue_scripts_styles_init() {

wp_enqueue_script( 'ajax-script', get_template_directory_uri().'./personalizetest.php', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
 }
  add_action('init', 'enqueue_scripts_styles_init');
?>

jQuery代码

$(document).ready(function(){
$('.button').click(function(){
    var clickBtnValue = $(this).val();
    var ajaxurl = 'personalizetest.php',
    data =  {'action': clickBtnValue};
    $.post(ajaxurl, data, function (response) {
        // Response div goes here.
        console.log("action performed successfully");
    });
});
<input type="submit" class="button" name="insert" value="insert" />

personalizetest.php(Swiftmailer代码)

 <?php
 require_once '/lib/config.php';
 require_once 'MyDecoratortest.php';

 function send_my_mail() {
 try {
//connect to database
$conn = new mysqli($root, $dbun, $dbps, $dbnm);
//get receipents
$recipients =[];
$sql = 'SELECT email, firstname, order_id,  FROM order_details order by _id desc limit 0, 1'; 
$result = $conn->query($sql);
$i = 0;
while ($row = $result->fetch_assoc()) {
     $recipients[$i]['email'] = $row['email'];
     $recipients[$i]['firstname'] = $row['firstname'];
     $recipients[$i]['order_id'] = $row['order_id'];
     $i++;    
 }

// create the transport
$transport = Swift_SmtpTransport::newInstance($smtp_server, 587, 'tls')
    ->setUsername($username)
    ->setPassword($password);
$mailer = Swift_Mailer::newInstance($transport);
// create and register decorator
$decorator = new Swift_Plugins_DecoratorPlugin(new MyDecorator($conn));
$mailer->registerPlugin($decorator);
//email
$html_message="My email text";
// prepare email message
$message = Swift_Message::newInstance()
    ->setSubject('Your Order at Dissertation Sage -- #order_id')
    ->setFrom($from)
    ->setBcc($bcc)
    ->setBody($html_message, 'text/html');

// tracking variables
$sent = 0;
$failures = [];
// send the personalized message to each recipient
foreach ($recipients as $recipient) {
    $message->setTo([$recipient['email'] => $recipient['firstname']]);
    $sent += $mailer->send($message);
  }
// display result
if ($sent) {
    echo "Number of emails sent: $sent<br>";
}
if ($failures) {
    echo "Couldn't send to the following addresses:<br>";
    foreach ($failures as $failure) {
        echo $failure . '<br>';
    }
    }
} catch (Exception $e) {
echo $e->getMessage();
}}?>

首先,您在wp_enqueue_script中包含了.php。如果ajax回调函数在personalizetest.php文件中,则需要使用将其包含在内

<?php
require_once( get_template_directory(). '/{your folder name here}/personalizetest.php' );
add_action('init', 'enqueue_scripts_styles_init');
function enqueue_scripts_styles_init() {
    wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/custom.js', array('jquery'), 1.0 ); // jQuery will be included automatically
    wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
 }
?>

在这里排队的脚本被称为custom.js,但您可以将其设置为用于调用ajax调用的任何脚本

js部分应该看起来像(在custom.js中):

jQuery(document).ready(function($){
$('.button').click(function(){
    var ajaxurl = ajax_object.ajaxurl,
    data =  {'action': 'my_action'};
    $.post(ajaxurl, data, function (response) {
        // Response div goes here.
        console.log("action performed successfully");
    });
});

该操作应该指向位于personalizetest.php文件中的ajax回调函数,使用钩子:

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

(更改动作ofc的名称)。

你可以阅读我写的关于ajax加载的博客文章,这是针对帖子的,但同样的原则也适用于这里:

AJAX加载WordPress 上的帖子