Custom API Development of outside the usual WordPress custom post type data fetching

Custom API Development of outside the usual WordPress custom post type data fetching

To create an API for a custom post type taxonomy in WordPress using wp-load.php, you can create a standalone PHP script that loads the WordPress environment and fetches the taxonomy terms. This is particularly useful if you need to create a custom API outside the usual WordPress REST API structure or for custom data fetching.

Step 1: Create the PHP File

Create a new file called custom-api.php and place it in the root of your WordPress installation or a suitable directory.


Step 2: Add Code to Load WordPress Environment and Fetch Data

Add the following code to custom-api.php:

<?php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');
  
$path = dirname(__DIR__, 3);
$wp_load = $path.'\wp-load.php'; 
 
require($wp_load); 

if(isset($_POST['state_slug'])){
    
    $slug = $_POST['state_slug']; 
    $result =  array(); 

        $args = array( 'post_type' => 'taxonomy_name', 'taxonomy_name'=> 'category_name');
    
        $the_query = new WP_Query( $args ); ?>
 

        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        
            <?php 
                
                $result[] = array(
                    'title' => get_the_title(), 
                    'content' => get_the_content(), 
                    );

                ?>

            <?php endwhile;

                wp_reset_postdata(); ?>
  
            <?php
            // Encode the data to JSON format and output it
            
                $response = array(
                    'result' => 'Success',
                    'data' => $result
                );
    
                header('Content-type: application/json; charset=utf-8');
                echo json_encode($response);
                ?>

            <?php
                }
            ?>        

Step 3: Access the API

Access the script in your browser or via an HTTP request:

http://localhost/myfreeonlinetools/wp-content/themes/myfreeonlinetools-blog/custom-api.php



To view or add a comment, sign in

More articles by Rajvinder Singh

Insights from the community

Others also viewed

Explore topics