有几种方法可以使you\'r表单在站点上可见:
用表单包装快捷代码/小部件创建页面模板有几种方法可以在php中处理表单:
将处理直接添加到页面模板的php文件中,在init/wp或任何其他操作中添加处理,在ajax操作中添加处理,我将如何执行这些操作:
创建页面模板将表单插入其中,仅将这些页面模板的脚本和样式排队<?php echo admin_url( \'admin-ajax.php\' ); ?>
添加隐藏输入name="action"
和value="my_form_action"
创建ajax操作add_action( \'wp_ajax_my_form_action\', \'my_form_function\' );
和add_action( \'wp_ajax_nopriv_my_form_action\', \'my_form_function\' );
_nopriv
用于未登录用户创建表单处理功能my_form_function
示例:模板我的表单。php
<?php
/* Template Name: My Form Template */
get_header();
// here goes form..
// you can copy index.php, rename it and insert your form
// where starts if( have_posts() )
?><form action="<?php echo admin_url( \'admin-ajax.php\' ); ?>">...</form><?php
get_footer();
功能。php
add_action( \'wp_ajax_my_form_action\', \'my_form_function\' );
add_action( \'wp_ajax_nopriv_my_form_action\', \'my_form_function\' );
function my_form_function() {
$form_element = sanitize_text_field( $_REQUEST[\'form_name\'] );
// here you do what you\'r form should do
// remember that you\'r now in admin-ajax.php
// so you need to redirect back to your page
// check wp_referer_field and wp_nonce_field
// if you want to make js ajax calls you should do wp_send_json_success( array );
}
add_action( \'wp_enqueue_scripts\', \'my_form_scripts\' );
function my_form_scripts() {
if( is_page_template( \'template-my-form.php\' ) ) {
wp_enqueue_scripts(\'my_file\', get_stylesheet_directory_uri() . \'/js/my_script.js\', array( \'jquery\' ) );
}
}
my\\u脚本。js公司
$(document).on( \'submit\', \'form\', function( event ) {
var $ajax = $(this).find( \'input[name="ajax"]\' );
if( $ajax.length < 1 || parseInt( $ajax.val() ) < 1 )
return;
$.ajax( {
action: $(this).attr( \'action\' ),
data: $(this).serialize(),
success: function( res ) {
if( res.success ) {
// do on success form proccessing
// res.data holds array passed to wp_send_json_success
} else {
// do on error form proccessing
// res.data holds array passed to wp_send_json_error
}
}
} );
} );