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

问题描述 投票:0回答:1

我已经创建了一个插件来充当某些请求的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获得产品对象。该产品是可预订的产品,它仍然存在于数据库中。

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

php wordpress
1个回答
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;
 }

}
© www.soinside.com 2019 - 2024. All rights reserved.