我正在使用woocommerce,我正在为我的产品使用自定义帖子类型(产品)
这是将我的自定义帖子类型集成到woocommerce的代码
class WCCPT_Product_Data_Store_CPT extends WC_Product_Data_Store_CPT {
/**
* Method to read a product from the database.
* @param WC_Product
*/
public function read( &$product ) {
$product->set_defaults();
if ( ! $product->get_id() || ! ( $post_object = get_post( $product->get_id() ) ) || ! in_array( $post_object->post_type, array( 'products', 'product' ) ) ) {
throw new Exception( __( 'Invalid product.', 'woocommerce' ) );
}
$id = $product->get_id();
$product->set_props( array(
'name' => $post_object->post_title,
'slug' => $post_object->post_name,
'date_created' => 0 < $post_object->post_date_gmt ? wc_string_to_timestamp( $post_object->post_date_gmt ) : null,
'date_modified' => 0 < $post_object->post_modified_gmt ? wc_string_to_timestamp( $post_object->post_modified_gmt ) : null,
'status' => $post_object->post_status,
'description' => $post_object->post_content,
'short_description' => $post_object->post_excerpt,
'parent_id' => $post_object->post_parent,
'menu_order' => $post_object->menu_order,
'product_id' => $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id(),
'reviews_allowed' => 'open' === $post_object->comment_status,
'price' => $post_object->price
) );
$this->read_attributes( $product );
$this->read_downloads( $product );
$this->read_visibility( $product );
$this->read_product_data( $product );
$this->read_extra_data( $product );
$product->set_object_read( true );
}
public function get_product_type( $product_id ) {
$post_type = get_post_type( $product_id );
if ( 'product_variation' === $post_type ) {
return 'variation';
} elseif ( in_array( $post_type, array( 'products', 'product' ) ) ) { // change birds with your post type
$terms = get_the_terms( $product_id, 'product_type' );
return ! empty( $terms ) ? sanitize_title( current( $terms )->name ) : 'simple';
} else {
return false;
}
}
}
add_filter( 'woocommerce_data_stores', 'woocommerce_data_stores' );
function woocommerce_data_stores ( $stores ) {
$stores['product'] = 'WCCPT_Product_Data_Store_CPT';
return $stores;
}
所以我知道可以通过在其上添加价格来将自定义帖子类型添加到购物车
我使用woocommerce_form_field()添加了一个自定义字段,称为“跟踪长度”,每24美元会乘以2(2 x $ 24 = $ 28)
现在,我尝试使用“ woocommerce_before_calculate_totals”过滤器,但该过滤器不起作用,set_price()无效,这可能是因为其自定义帖子类型
所以现在我在“ woocommerce_product_get_price”过滤器中获取了计算结果,但它不适用于购物车中的每个项目
这是我的函数中的代码。phphttps://codeshare.io/5eN797