WordPress custom page template and WP-API

My WordPress site uses custom template pages like this one:

<php
 /* 
  Template Name : project_costs
 /*

get_header ();

// set default vars or user received
require("my_forms.php");
// pull data from db and calculate
require("project_calculation. php");
// create page
require("content. php");
...

My custom page project_costs.php performing the steps :

Read More
  1. Receive and set user entered vars from page forms (POST/GET).
  2. Pull data from database.
  3. Do some calculations and changes.
  4. Creates page for user. 

I want to integrate angular.js with the WP-API plugin. The plugin just pulls raw data from database (step 2) and sends it to front end (step 4). So pages and templates not in use as page didn’t reload.

I want to pass data to my php class first (step 3), then pass changed data to WP-API.

Is there any function in WP-API to call my PHP file or function? 

Any advice, samples or links would be highly appreciated.

Thanks.

Related posts

1 comment

  1. So I’m working on a huge project which includes several API/Angular replacement parts for #WordPress. One file is a custom endpoint-boilerplate.php. It works like a charm so far but any input would be appreciated.

    Just follow the structure and use the my_awesome_function to return do anything you’d like. Then the namespace and route from the hook will be available, using data from my_awesome_func.

    <?php 
    /* ------------------------------------------------------------------------ *  
        A great example of custom endpoints is the PHP in wp-api-menus plugin
    * ------------------------------------------------------------------------ */
    
    // hook into rest_api_init and register a new api route
    add_action( 'rest_api_init', function () {
    
    register_rest_route( 
        'custom-endpoint/v2',   // namespace
        '/author/(?P<id>d+)',  // route
        array(                  // options
            'methods'  => 'GET',
            'callback' => 'my_awesome_func',
            // 'args'     => array(
            //     'context' => array(
            //     'default' => 'view',
            //     ),
            // ) 
        )
    );
    
    });
    
    
     function my_awesome_func( $data ) {
        $posts = get_posts( array(
            'author' => $data['id'],
        ) );
    
        if ( empty( $posts ) ) {
            return null;
        }
    
        return $posts[0]->post_title;
    }
    

    So your call will then be a get to http://yourproject.com/wp-json/custom-endpoint/v2/author/1

Comments are closed.