0

I need to create a post endpoint for a contact form that any user (not just logged in users) can use. The post is made via AJAX/REST.

Is the industry standard way to do this via a new WP REST endpoint? Ie,

add_action( 'rest_api_init', function () {
    register_rest_route( 'mytheme/v1', '/contact', array(
        'methods' => 'POST',
        'callback' => 'my_awesome_func',
    ) );

Or should we use the WP API and register a post action/filter/hook?

  • the WP API is easier to use when you return JSON. in other case you can use WP AJAX. in both case you can test if the user is connected and you can access to all WordPress objects. – mmm Apr 26 '18 at 7:48
0

You can use wp_ajax action:

add_action( 'wp_ajax_my_awesome_ajax', 'my_awesome_func' );
add_action( 'wp_ajax_nopriv_my_awesome_ajax', 'my_awesome_func' );

function my_awesome_func() {
  // Handle request with $_POST

  wp_die();
}

You can submit contact form with jQuery post:

jQuery.post(
  my_awesome_js.ajaxurl, 
  {
    'action': 'my_awesome_ajax',
    'data': 'some data'
  },
  function(response){
    alert(response);
  }
);

The my_awesome_js.ajaxurl you use wp_localize_script:

wp_enqueue_script('my_awesome_js', '/path/to/your/script/above.js', array('jquery'));
wp_localize_script('my_awesome_js', 'my_awesome_js', array(
   'ajaxurl' => admin_url('admin-ajax.php')
));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.