如何在外部文件中使用WordPress is_email()函数


how to use wordpress is_email() function in external file

我正在编写一个外部php脚本,该脚本将在我的一个WP页面中从ajax调用。我希望这个脚本能够使用wordpress函数。这是我到目前为止所做的:

require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );

这允许我访问$wpdb对象。好。但我也想使用is_email()函数,也许还有其他本机 WP 函数。现在我遇到了"Call to undefined function is_email()..."致命错误。任何建议表示赞赏

你做错了。WP很高兴为您提供所需的功能。您应该在插件/主题functions.php文件中声明处理程序,并为wp_ajax_my_action注册一个处理程序(该示例取自 WP Codex):

<?php 
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
    global $wpdb; // this is how you get access to the database
    $whatever = intval( $_POST['whatever'] );
    $whatever += 10;
    echo $whatever;
    wp_die(); // this is required to terminate immediately 
              // and return a proper response
}

更多信息。

也许不是最优雅的方式,但至少它对我有用。

在函数中.php

add_action( 'wp_enqueue_scripts', 'localize_scripts');
  function localize_scripts() {
  wp_localize_script('jquery', 'urls', array( 'ajaxurl' => admin_url('admin-ajax.php') )); 
} 

在JavaScript内部

$.ajax({
    url: urls.ajaxurl,
    data: {
        'action':'my_function',
        'otherData': someString //variable
          },
    cache: false,
    success: function() {},
    error: function() {}
});

再次在函数中.php

function my_function() {
  // The $_REQUEST contains all the data sent via ajax
  if ( isset($_REQUEST) ) { 
    $someString = $_REQUEST['otherData'];
    echo $someString;
    // Always die in functions echoing ajax content
    die();
  }
}
add_action( 'wp_ajax_my_function', 'my_function' );