how to post form to another php file in wordpress?

2019-07-13 12:12发布

问题:

So my app theme structure is

-wp-content
  -themes
   -cool
    -templates
     -landing.php
     - post-landing.php

I have a form in landing.php and I want to handle POST request in post-landing.php for which I have,

form action="wp-content/themes/cool/templates/post-landing.php"

But when I make a post request it says 404.

回答1:

You cannot (and shouldn't) call the php files in wp themes directly. One way to do this is to create landing.php and post-landing.php as wp_template files. Then create Pages using these templates from the Wp-admin. And then landing.php use the link of the pages created with that post-landing.php template as the action to the form.



回答2:

Here's another way: in case you want to manage that asynchronously, you can create an AJAX call like this(I usually place it in my <theme>/inc folder, so it's automatically loaded):

add_action( 'wp_ajax_nopriv_<call_name>', '<function name>' );
add_action( 'wp_ajax_<call_name>', '<function name>' );

function <function_name>() {//here you do things with $_POST and return json}

Localize it in your functions.php file in order to have your ajaxUrl for the request always available in a variable and only for your js file:

wp_localize_script( 'enqueued-js-name', 'varName', array(
    'ajaxUrl' => admin_url( 'admin-ajax.php' )
));

And then you can call it like this in your enqueued JS file:

jQuery.ajax({
    url: varName.ajaxUrl,
    type: 'post',
    data: currentDataToSubmit,
    success: function(response){
       //manage the response
    }
});

And that's it! hope it was useful!

If there's something wrong with the first part, let me know, so I can learn too!