Showing posts with label rest api. Show all posts
Showing posts with label rest api. Show all posts

Wednesday, January 11, 2023

WordPress REST API Tutorial (Real Example)

 WordPress comes with a built-in (as in no plugins required) REST API. In this lesson we learn how to load and save content to/from the WordPress database on the fly using AJAX and the brand new REST API.

This is work only for admin login users.



1 : Open theme's functions.php file and paste these code.

//new code

    wp_enqueue_script( 'main_js', get_template_directory_uri() . '/rest/js/newcustom.js', NULL, '1.1', true );

    wp_localize_script('main_js', 'magicalData', array( 'nonce' => wp_create_nonce('wp_rest') )); 


2 : Create page-restapi.php in theme template path. put this code.

get_header(); ?>


    <div id="primary-mono" class="content-area col-md-12 page">

        <main id="main" class="site-main" role="main">


            <?php //if (current_user_can('administrator')) : ?>

            <div class="admin-quick-add">

                <h3>Quick Add Post</h3>

                <input type="text" name="title" placeholder="Title">

                <textarea name="content" placeholder="Content"></textarea>

                <button id="quick-add-button">Create Post</button>

            </div>

            <?php //endif; ?>



            <?php while ( have_posts() ) : the_post();?>

                <?php get_template_part( 'modules/content/content', 'page' ); ?>


                <?php

                // If comments are open or we have at least one comment, load up the comment template

                if ( comments_open() || get_comments_number() ) :

                    comments_template();

                endif;

                ?>


            <?php endwhile; // end of the loop. ?>

            <button  id="load-post-btn">Load Post</button>

            <div id="load_post_container"> </div>


        </main><!-- #main -->

    </div><!-- #primary -->


<?php get_footer(); ?>


3 : Create new js file in this theme path:/rest/js/newcustom.js

let load_post_btn = document.getElementById('load-post-btn');

var postcontainer = document.getElementById('load_post_container');


if (load_post_btn) {

load_post_btn.addEventListener("click", function(){

//console.log("clicked");

var ourRequest = new XMLHttpRequest();

// http://localhost/wordpress611/?rest_route=/wp/v2/posts

// http://localhost/wordpress611/wp-json/wp/v2/posts?categories=6&order=asc

ourRequest.open('GET', 'http://localhost/wordpress611/?rest_route=/wp/v2/posts');

ourRequest.onload = function() {

  if (ourRequest.status >= 200 && ourRequest.status < 400) {

    var data = JSON.parse(ourRequest.responseText);

    //console.log(data);

    createHTML(data)

  } else {

    console.log("We connected to the server, but it returned an error.");

  }

};


ourRequest.onerror = function() {

  console.log("Connection error");

};


ourRequest.send();


});

}


function createHTML(postsData) {

  var ourHTMLString = '';

  for (i = 0; i < postsData.length; i++) {

    ourHTMLString += '<h2>' + postsData[i].title.rendered + '</h2>';

    ourHTMLString += postsData[i].content.rendered;

  }

  postcontainer.innerHTML = ourHTMLString;

}


// Quick Add Post AJAX

var quickAddButton = document.querySelector("#quick-add-button");


if (quickAddButton) {

  quickAddButton.addEventListener("click", function() {

    var ourPostData = {

      "title": document.querySelector('.admin-quick-add [name="title"]').value,

      "content": document.querySelector('.admin-quick-add [name="content"]').value,

      "status": "publish"

    }


    var createPost = new XMLHttpRequest();

    var posturl = 'http://localhost/wordpress611/?rest_route=/wp/v2/posts';

    //createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/posts");

    createPost.open("POST", posturl);

    createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);

    createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    createPost.send(JSON.stringify(ourPostData));

    createPost.onreadystatechange = function() {

      if (createPost.readyState == 4) {

        if (createPost.status == 201) {

          document.querySelector('.admin-quick-add [name="title"]').value = '';

          document.querySelector('.admin-quick-add [name="content"]').value = '';

        } else {

          alert("Error - try again.");

        }

      }

    }

  });

}

4: add css:-

/* Quick Add Form Styles */

.admin-quick-add {

background-color: #DDD;

padding: 15px;

margin-bottom: 15px;

}


.admin-quick-add input,

.admin-quick-add textarea {

width: 100%;

border: none;

padding: 10px;

margin: 0 0 10px 0;

box-sizing: border-box;

}