[英]Extending the woocommerce rest api
我想擴展 woocommerce rest api 以包含其“預訂”擴展插件的數據。 目前這個擴展沒有由 rest api 提供的默認端點。
到目前為止,我已經創建了一個插件,並添加了以下代碼;
add_filter( 'woocommerce_rest_prepare_product', 'custom_data');
function custom_data($response, $object) {
if( empty( $response->data ) )
return $response;
$response->data['meta_data'] = get_post_meta( $object[ID], 'availability', true);
return $response;
}
當我調用端點/products
僅 woocommerce 概述的默認數據仍然被稱為我的小插件無處可尋。
我什至不知道在哪里可以找到上述過濾器,因為我剛剛在網頁上看到了這個,我試圖讓它做我想做的事,也不知道這是否是正確的方向。 網頁: https : //francescocarlucci.com/woocommerce/woocommerce-api-custom-data-default-endpoints/#more-96
以上是我試圖擴展 api 但我也決定嘗試創建一個自定義端點以查看是否可以獲得我想要的結果但到目前為止我剛剛創建了一個調用的端點但我不知道要寫什么來檢索我想要的數據。
自定義端點代碼:
function register_custom_route() {
register_rest_route( 'ce/v1', '/bookable',
array(
'methods' => 'GET',
'callback' => 'get_bookable'
)
);
}
function get_bookable( ) {
return array( 'custom' => 'woocommerce here' );
//What code do I write here :(
}
無論如何,我可以通過上述方法之一實現我想要的嗎? 我對開發人員很陌生,我熟悉 javascript 而不是 PHP,因此我需要使用其余的 api,因為我想使用 wordpress/woocommerce 作為無頭 cms。
到目前為止,我所使用的壁櫥示例已在此問題創建 WooCommerce 自定義 API 中顯示
或者,您可以嘗試使用以下代碼來擴展 WooCommerce REST API 的產品響應,而無需額外執行,因為您上面的鈎子“woocommerce_rest_prepare_product”適用於v1,但目前它是v3,因此最新的鈎子低於一個(下面的鈎子來自 v2由 v3 擴展的 rest api 控制器)。
add_filter('woocommerce_rest_prepare_product_object', 'so54387226_custom_data', 10, 3);
function so54387226_custom_data($response, $object, $request) {
if (empty($response->data))
return $response;
$id = $object->get_id(); //it will fetch product id
$response->data['booking_meta_data'] = get_post_meta($id, 'availability', true);
return $response;
}
我測試了上面的代碼它工作得很好。 希望它可以幫助尋找類似解決方案的人。
這只是我代碼的一部分。 一些未定義的變量。 而這只是概念。 希望您可以根據您的要求進行修改。
public function __construct() {
$this->template_url = apply_filters( 'woocommerce_template_url', 'woocommerce/'
);
$this->api_namespace = 'wc/v';
$this->base = 'home';
$this->api_version = '2';
add_action( 'woocommerce_loaded', array( $this, 'register_hooks' ) );
}
$namespace = $this->api_namespace . $this->api_version;
register_rest_route(
$namespace, '/wclogin/',
array(
'methods' => 'GET',
'callback' => array( $this, 'wc_login'),
)
);
function wc_login($request){
$user = get_user_by('email', $request["email"]);
//bad email
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}
else{ //check password
if(!wp_check_password($request["password"], $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>ERROR</strong>: Either the email or password you entered is invalid.'));
return $error;
}else{
return $user; //passed
}
}
}
只是對那些提出這個問題的人的更新。 現在,預訂擴展有一個休息 api: https : //docs.woocommerce.com/document/bookings-rest-api-reference/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.