简体   繁体   中英

WP Rest API Ajax Post method to update page content

I am testing out WP Rest API ajax method to replace admin-ajax.php method with it. I can't quite figure our how can I refresh my post content with WP Rest API. Currently I have my Ajax functions set up like this. My idea is that the page should show 20 products after ajax call instead of 10.

my jQuery Ajax

$(document).on("click", '.js-show-more', function (e) {
            e.preventDefault();    
            $.ajax({
                type: 'POST',
                url: myObj.restURL + 'baseUrl/v1/baseEndPoint/endPoint',
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-WP-Nounce', myObj.restNounce);
                },
                data: {
                    showMore: productCount,
                },
                success: function (response) {
                    if (response) {
                        console.log(response); //testing what's in the response
                        $('.js-more-products').html(response);  //updating div with response data
                    }
                }
            });
        });

My endpoint in functions.php

 wp_enqueue_script('js', get_template_directory_uri() . '/dist/my-javascript-file.min.js', array(), filemtime(get_stylesheet_directory() . '/dist/my-javascript-file.min.js'), true);
  wp_localize_script('js', 'myObj', array(
    'restURL' => rest_url(),
    'restNonce' => wp_create_nonce('wp_rest')
  ));

add_action('rest_api_init', function () {
  register_rest_route('baseURL/v1/baseEndPoint', '/endPoint/', array(
    'methods' => 'POST',
    'callback' => 'restAPI_endpoint_callback'
  ));
});

function restAPI_endpoint_callback()
{
      $myContent = file_get_contents(get_template_directory() . '/templates/more-products.php', true);
  return json_encode($myContent);
  die;
}

My template file

$published_posts = wp_count_posts('product')->publish;

if (!empty($_POST['showMore'])) :
    $perPage = (int)$_POST['showMore'];
else :
    $perPage = 10;
endif;

$args = array(
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'ignore_sticky_posts'   => 1,
    'posts_per_page'        => $perPage,
);
$products = new WP_Query($args);

Doing this for learning purposes since I heard that it's much better to use WP Rest API instead of admin-ajax.php. Any kind of new info or help is really appreciated. Cheers!

EDIT: Changed my restAPI_endpoint_callback endpoint to return template content. Right now it returns file as text content instead of html

After testing out some stuff I solved it like this. Feels faster than admin-ajax.php but unsure if this can be considered as the right technique.

function restAPI_endpoint_callback()
{
  ob_start();
  require(get_template_directory() . '/templates/more-products.php');
  $template = ob_get_contents();
  ob_end_clean();
  return $template;
}

If someone is more familiar with something like this then feel free to have a discussion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM