WC_REST_Products_V1_Controller::prepare_item_for_database
Prepare a single product for create or update.
Method of the class: WC_REST_Products_V1_Controller{}
Hooks from the method
Returns
WP_Error|stdClass. $data Post object.
Usage
// protected - for code of main (parent) or child class $result = $this->prepare_item_for_database( $request );
- $request(WP_REST_Request) (required)
- Request object.
WC_REST_Products_V1_Controller::prepare_item_for_database() WC REST Products V1 Controller::prepare item for database code WC 10.6.2
protected function prepare_item_for_database( $request ) {
$id = isset( $request['id'] ) ? absint( $request['id'] ) : 0;
// Type is the most important part here because we need to be using the correct class and methods.
if ( isset( $request['type'] ) ) {
$classname = WC_Product_Factory::get_classname_from_product_type( $request['type'] );
if ( ! class_exists( $classname ) ) {
$classname = 'WC_Product_Simple';
}
$product = new $classname( $id );
} elseif ( isset( $request['id'] ) ) {
$product = wc_get_product( $id );
} else {
$product = new WC_Product_Simple();
}
// Post title.
if ( isset( $request['name'] ) ) {
$product->set_name( wp_filter_post_kses( $request['name'] ) );
}
// Post content.
if ( isset( $request['description'] ) ) {
$product->set_description( wp_filter_post_kses( $request['description'] ) );
}
// Post excerpt.
if ( isset( $request['short_description'] ) ) {
$product->set_short_description( wp_filter_post_kses( $request['short_description'] ) );
}
// Post status.
if ( isset( $request['status'] ) ) {
$product->set_status( get_post_status_object( $request['status'] ) ? $request['status'] : ProductStatus::DRAFT );
}
// Post slug.
if ( isset( $request['slug'] ) ) {
$product->set_slug( $request['slug'] );
}
// Menu order.
if ( isset( $request['menu_order'] ) ) {
$product->set_menu_order( $request['menu_order'] );
}
// Comment status.
if ( isset( $request['reviews_allowed'] ) ) {
$product->set_reviews_allowed( $request['reviews_allowed'] );
}
/**
* Filter the query_vars used in `get_items` for the constructed query.
*
* The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being
* prepared for insertion.
*
* @param WC_Product $product An object representing a single item prepared
* for inserting or updating the database.
* @param WP_REST_Request $request Request object.
*/
return apply_filters( "woocommerce_rest_pre_insert_{$this->post_type}", $product, $request );
}