HTML表单action字段无法跳转至指定PHP文件的问题求助
Hey there! Let's work through this path confusion you're hitting with your WordPress plugin's form actions. Since you're operating within WordPress, ditching hardcoded relative/absolute local paths and using WordPress's built-in URL functions is the way to go—this avoids environment-specific issues and keeps things aligned with WP's structure.
Here are the actionable solutions tailored to your setup:
1. Use site_url() to Generate a Web-accessible Absolute URL
WordPress's site_url() function returns your site's root web URL (e.g., http://localhost/cbjaxon), which you can append your Code directory path to.
In your schoolMaint01-tpl.php template, set the form's action like this:
<form action="<?php echo site_url('/Code/schoolInsert.php'); ?>" method="POST" onsubmit="return validateFormOnSubmit()"> <!-- Your form fields here --> </form>
Then, in schoolInsert.php, after processing the data, use WordPress's wp_redirect() to jump back to your template—don't forget to add exit; right after to stop any further code execution:
// After handling insert logic... wp_redirect(site_url('/wp-content/plugins/cgdmaintroutines/templates/schoolMaint01-tpl.php')); exit;
2. Ensure Your Business Files Have Access to WordPress Environment (If Needed)
If your schoolInsert.php needs to use WordPress functions (like wp_redirect() or database calls), you'll need to load WordPress's core first. Add this line at the very top of schoolInsert.php:
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
This pulls in WordPress's core files so your business script can interact with the WP ecosystem properly.
3. (Recommended) Move Business Files to Your Plugin Directory
For better maintainability (and to avoid relying on root-level paths), consider moving your Code folder into your plugin directory (cgdmaintroutines/Code). Then you can use plugin_dir_url() to generate the path dynamically:
In your template:
<form action="<?php echo plugin_dir_url(__FILE__) . '../Code/schoolInsert.php'; ?>" method="POST" onsubmit="return validateFormOnSubmit()"> <!-- Form fields --> </form>
(Note: __FILE__ refers to the current template file, so ../ moves up one directory to the plugin root, then into the Code folder.)
For the redirect in schoolInsert.php (now in plugin/Code):
wp_redirect(plugin_dir_url(__FILE__) . '../templates/schoolMaint01-tpl.php'); exit;
Quick Checks to Verify
- Inspect your page's source code to confirm the form's
actionattribute shows a valid web URL (likehttp://localhost/cbjaxon/Code/schoolInsert.php), not a local file path (e.g.,C:\Wamp64...—browsers can't use these!). - Double-check your form's
methodmatches what your PHP script expects (most oftenPOSTfor insert/update actions).
内容的提问来源于stack exchange,提问作者Charles Jackson

