最后,在尽了最大努力之后,我在这里以简单的步骤分享我的问题的完整基本示例。这个答案也被认为是一个完整的Ajax插件示例。我现在建议将每个文件分开,以便更好、干净和舒适地编码。。。
Main Plugin File:
<?php
/*
Plugin Name: WP Testing Plugin
Plugin URI: http://www.wordpress.org/WP-Testing-Plugin
Description: A Detailed Description About This Plugin.
Author: Muhammad Hassan
Version: 0.1
Author URI: http://www.wordpress.org
*/
// Calling All PHP File To Load
include(\'my_functions.php\');
/*____________WP Testing Plugin Admin/Script_____________*/
function wp_testingPlugin_admin() {
echo \'
<form id="searchForm">
<input name="WhatToSearch" type="text" />
<input type="submit" value="Search"/>
<input type="reset" value="Reset"/>
<div id="showReturnData"></div>
</form>
\';
}
/*__________________________________________________________________*/
/*____________WP Testing Plugin Option_____________*/
//Adding "WP Testing Plugin" Menu To WordPress -> Tools
function wp_testingPlugin() {
// add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function); Menu Under Tools
add_management_page("WP Testing Plugin By Hassan", "WP Testing Plugin", \'activate_plugins\', "WP-Testing-Plugin", "wp_testingPlugin_admin");
}
add_action(\'admin_menu\', \'wp_testingPlugin\');
/*__________________________________________________________________*/
?>
my_functions.php
<?php
add_action( \'admin_enqueue_scripts\', \'my_enqueue\' );
function my_enqueue() {
wp_enqueue_script( \'ajax-script\', plugin_dir_url( __FILE__ ).\'my_javascript.js\', array(\'jquery\') );
wp_localize_script( \'ajax-script\', \'my_ajax_object\', array( \'ajax_url\' => admin_url( \'admin-ajax.php\' ) ) );
}
/****************************************************************************/
// Run Search Function
/****************************************************************************/
/* Register This Function When This File Is Loaded To Call By WordPress AJAX */
add_action(\'wp_ajax_nopriv_SearchFunction\', \'ajaxSearchFunction\'); // For Web Visitors
add_action(\'wp_ajax_SearchFunction\', \'ajaxSearchFunction\'); // For Admin User
function ajaxSearchFunction(){
if($_POST[\'WhatToSearch\'] == ""){
$WhatToSearch = "Nothing";
} else {
$WhatToSearch = $_POST[\'WhatToSearch\'];
}
echo "<div class=\'success\'>SUCCESS: Function Is Working Perfectly And Getting Data ".$WhatToSearch.".</div>";
}
?>
my_javascript.js
jQuery(document).ready(function() {
jQuery(\'#searchForm\').on("submit",function(e) {
var incomingData = jQuery(\'#searchForm\').serializeArray();
incomingData.push({name: \'action\', value: \'SearchFunction\'});
alert(JSON.stringify(incomingData));
jQuery.ajax({
type: \'post\',
url: my_ajax_object.ajax_url,
data: incomingData,
success: function(response) {
jQuery(\'#showReturnData\').html(response);
},
error: function(response) {
jQuery(\'#showReturnData\').html(\'<div">Error</div>\');
},
});
return false; // For Not To Reload Page
});
});
感谢您阅读本文。