Ajax
Working with AJAX Using Custom Endpoints or WordPress Endpoints
AJAX (Asynchronous JavaScript and XML) allows you to send and retrieve data asynchronously from the server without refreshing the page. This is particularly useful for improving user experience, as it enables dynamic content updates without full page reloads. In WordPress, you can interact with AJAX by creating custom endpoints or using the built-in WordPress endpoints.
1. Using custom endpoints
- Backend:
- Registers an API endpoint (wp/v2/tf_api/get_results).
- Processes parameters (keyword, etc.) and queries WordPress posts.
- Returns JSON data or error responses.
- Frontend:
- Sends GET requests to the API endpoint with appropriate query parameters.
- Processes the response to display or handle search results dynamically. This setup provides a clean separation of concerns, making it reusable and extendable for future needs. Let’s see a proper example of how to consume a custom REST API endpoint in WordPress using PHP for backend functionality and JavaScript for frontend integration.
PHP backend
Create a REST API endpoint (/get_results) that fetches search results based on a object or parameters like keyword in this example of a search.
Implementation:
- Registers the custom endpoint using a helper class when using terraClasses.
- The endpoint retrieves posts of types page and updates, including details like title, permalink, and type.
- Utilizes WordPress’s WP_Query for custom queries.
- Responds with results in JSON or an error if no results are found.
function get_search_results($request) { $modifiedSpaces = str_replace('%20', ' ', $request['keyword']); $search = strtolower($modifiedSpaces);
$args = array( 'post_type' => array('page', 'updates'), 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'relevance', 'order' => 'ASC', );
$query = new WP_Query($args);
if (!$query->have_posts()) { return rest_ensure_response(new WP_Error('no_results', 'No results found', array('status' => 404))); }
$results = array();
while ($query->have_posts()) { $query->the_post();
$post_id = get_the_ID(); $post_type = get_post_type($post_id); $post_title = get_the_title(); $permalink = get_permalink($post_id);
$results[] = (object) array( 'post_type' => $post_type, 'post_title' => $post_title, 'permalink' => $permalink, ); }
wp_reset_postdata(); return rest_ensure_response($results);}
new Custom_API_Endpoint((object) array( 'namespace' => 'wp/v2/tf_api/', 'route' => '/get_results', 'method' => 'GET', 'callback_function' => 'get_search_results',));
JavaScript frontend
Fetch data from the custom REST API endpoint using parameters like keyword, in this example, or other object.
Implementation:
- Utilizes axios for asynchronous HTTP requests.
- Builds a dynamic URL using settings derived from the payload.
- Catches errors and returns fetched data or null if the request fails.
const fetchResults = async (keyword) => { try { const response = await GET_CUSTOM_ENDPOINT({ ACTION: "get_results", keyword: keyword, }); console.log(response.data); } catch (error) { console.error("Error fetching results:", error); }};fetchResults("example search");
export const GET_CUSTOM_ENDPOINT = async (payload) => { let receivedData = null; var settings = { action: payload.ACTION, page_id: payload.PAGE_ID, location: payload.location, sector: payload.sector, }; try { receivedData = await axios.get( `${siteURL}/wp-json/wp/v2/tf_api/${settings.action}?location=${settings.location}§or=${settings.sector}&page_id=${settings.page_id}` ); } catch (error) { console.log(error); } return receivedData;};
GET_CUSTOM_ENDPOINT lives inside the services/GET folder as index.js.
2. Using WordPress default endpoints
WordPress already provides built-in endpoints for various tasks like fetching posts or submitting forms, such as the wp-admin/admin-ajax.php endpoint. This endpoint allows you to use AJAX without creating a custom handler.
For example, wp_ajax_* actions are part of the default WordPress AJAX mechanism. When you send a request to admin-ajax.php, WordPress will trigger the appropriate action based on the action parameter.
You can extend these default endpoints or use them directly for tasks like form submission or getting post data.
3. Using ACF to Rest Api plugin
The ACF to REST API plugin exposes ACF fields as part of the WordPress REST API, making it easier to integrate custom fields into your application by querying them through standard API endpoints.
Implementation:
- Once the plugin is installed, the ACF fields will be available via REST API endpoints.
- The ACF fields will be included in the response of standard WordPress REST API responses (e.g., when querying a post).
- You can also fetch them directly using custom endpoints like /acf/v2/options.
- Now we can use this to create custom endpoints like this one to get the theme options fields:
export const GET_THEME_OPTIONS = async (payload) => { let receivedData = null; var settings = { action: payload.ACTION // e.g., 'options' }; try { // Axios request to fetch ACF data from a custom API endpoint receivedData = await axios.get( `${siteURL}/wp-json/acf/v2/${settings.action}` ); } catch (error) { console.log(error); // Handle any errors during the request } return receivedData; // Return the fetched data};