无法在api插件中使用wordpress功能

时间:2017-12-19 03:12:40

标签: php wordpress

我已经创建了一个插件来充当某个请求的api。它的结构如下:

add_action( 'rest_api_init', 'registerRoute' );

function registerRoute() {
  register_rest_route( 'test/v1/', 'mobile', array(
        'methods' => 'POST',
        'callback' => array(new testApi(), $_POST['action']),
    ));
}

class testApi
{
 .......
 public function getProduct()
 {
    $post_id = 123;
    var_dump(wc_get_product( $post_id ));exit;
 }
 .......
}

在上面的代码中,wc_get_product returns boolean(false)。我尝试了其他wordpress函数来查看它们是否返回任何值,即:

get_post($post_id);

  

wp_get_current_user();

  

并返回以下内容:

object(WP_User)#1772 (7) {
  ["data"]=>
  object(stdClass)#1773 (0) {
  }
  ["ID"]=>
  int(0)
  ["caps"]=>
  array(0) {
  }
  ["cap_key"]=>
  NULL
  ["roles"]=>
  array(0) {
  }
  ["allcaps"]=>
  array(0) {
  }
  ["filter"]=>
  NULL
}

所以,我在网上进行了一些搜索,并在我的文件上面添加了这段代码:

require_once(ABSPATH . 'wp-load.php');

当我回显ABSPATH时,它确实给了我路径字符串。我也可以使用$wpdb对象;

我想知道为什么我无法通过上面显示的产品ID获取产品对象。该产品是可预订的产品,它仍然存在于数据库中。

请告诉我,这里出了什么问题。

1 个答案:

答案 0 :(得分:0)

使用json_decode();

的产品对象显示
add_action( 'rest_api_init', 'registerRoute' );

function registerRoute() {
  register_rest_route( 'test/v1/', 'mobile', array(
        'methods' => 'POST',
        'callback' => array(new testApi(), $_POST['action']),
    ));
}

class testApi
{

 public function getProduct()
 {


    global $product;
    $_product = wc_get_product('215');

    $response = array(
            "result"=>true,
            "data" => json_decode($_product),
            "message"=>'Single Product'
            );

    return $response;
 }

}
相关问题