我有一个表单,它将字段值传递给jQuery,jQuery验证字段并创建发送的变量data: {}
在下面的代码段中。
$.ajax({
type: "POST",
url: "<?php bloginfo(\'stylesheet_directory\'); ?>/process.php",
dataType: "json",
data: {
"title":title,
"goals":goals,
"progress":progress,
"categories":categories,
"tags":tags,
"video":video,
"audio":audio,
},
success: function() {
//get permalink for post from php and go to it
}
});
process.php
未收到任何数据,或未发布数据。
我不知道为什么。
下面是我的process.php
文件:
<?php
$user_submitted_title = sanitize_text_field($_POST[\'user_submitted_title\']);
$user_submitted_progress = $_POST[\'user_submitted_progress\'];
$user_submitted_goals = $_POST[\'user_submitted_goals\'];
$user_submitted_categories = $_POST[\'user_submitted_categories\'];
$user_submitted_tags = sanitize_text_field($_POST[\'user_submitted_tags\']);
$user_submitted_video = sanitize_text_field($_POST[\'user_submitted_video\']);
$user_submitted_audio = sanitize_text_field($_POST[\'user_submitted_audio\']);
$user_post = array(
\'comment_status\' => \'open\',
\'post_author\' => $user_ID,
\'post_category\' => array($user_submitted_categories),
\'post_content\' => \'<h2>Project Progress</h2>\' . $user_submitted_progress . \'<h2>Project Goals</h2>\' . $user_submitted_goals,
\'post_status\' => \'publish\',
\'post_title\' => $user_submitted_title,
\'post_type\' => \'post\',
\'tags_input\' => $user_submitted_tags
);
$user_post_id = wp_insert_post($user_post);
add_post_meta($user_post_id, \'wpcf-video\', $user_submitted_video);
add_post_meta($user_post_id, \'wpcf-audio\', $user_submitted_audio);
$user_post_redirect = get_permalink($user_post_id);
?>
我需要弄清楚为什么在我使用表单时没有任何帖子,以及如何发送
$user_post_redirect
返回jQuery,以便重定向到它。
我如何才能做到这一点?
最合适的回答,由SO网友:Milo 整理而成
当您加载process.php
文件,它不在WordPress环境的上下文中,因此没有可用的WordPress函数。WordPress具有本机AJAX API 应该用在这类事情上。
第一enqueue your javascript file, 然后使用wp_localize_script
传递的位置admin-ajax.php
, 将处理请求:
function wpa_scripts() {
wp_enqueue_script(
\'wpa_script\',
get_template_directory_uri() . \'/js/script.js\',
array(\'jquery\'),
null,
true
);
$script_data = array(
\'admin_ajax\' => admin_url( \'admin-ajax.php\' )
);
wp_localize_script(
\'wpa_script\',
\'wpa_data\',
$script_data
);
}
add_action( \'wp_enqueue_scripts\', \'wpa_scripts\' );
接下来,添加
action
到ajax数据,该数据将映射到连接到处理请求的函数:
$.ajax({
type: "POST",
url: wpa_data.admin_ajax,
dataType: "json",
data: {
"action":"some_action",
},
success: function() {
//get permalink for post from php and go to it
}
});
最后,在php中添加动作,并将其挂接到将接收和处理它的函数,然后移动process的内容。此函数中的php
add_action( \'wp_ajax_some_action\', \'your_process_function\' );
add_action( \'wp_ajax_nopriv_some_action\', \'your_process_function\' );