2

我的 Wordpress 网站使用这样的自定义模板页面:

<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");
...

我的自定义页面project_costs.php 执行以下步骤:

  1. 从页面表单(POST/GET)接收和设置用户输入的变量。
  2. 从数据库中提取数据。
  3. 做一些计算和改变。
  4. 为用户创建页面。 

我想将angular.js与 WP-API 插件集成。该插件只是从数据库中提取原始数据(步骤 2)并将其发送到前端(步骤 4)。因此,未作为页面使用的页面和模板不会重新加载。

我想先将数据传递给我的 php 类(第 3 步),然后将更改的数据传递给 WP-API。

WP-API 中是否有任何函数可以调用我的 PHP 文件或函数? 

任何建议、样本或链接将不胜感激。

谢谢。

4

1 回答 1

4

所以我正在做一个巨大的项目,其中包括#WordPress 的几个 API/Angular 替换部件。一个文件是自定义端点样板.php。到目前为止,它就像一个魅力,但任何输入将不胜感激。

只需按照结构并使用my_awesome_function返回来做任何你想做的事情。然后使用来自 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;
}

所以你的电话将gethttp://yourproject.com/wp-json/custom-endpoint/v2/author/1

于 2016-03-03T21:43:50.470 回答