【发布时间】:2018-06-11 12:45:12
【问题描述】:
我正在使用以下代码将自定义帖子类型的自定义字段用作价格字段。这样我就可以将此字段值添加到购物车中并进行付款。
好消息是此自定义帖子已成功进入购物车但问题是价格值错误。
价格应为 400 美元,但显示为 51,376 美元。
代码如下:
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
// Put your plugin code here
add_action('woocommerce_loaded' , function (){
//Put your code here that needs any woocommerce class
//You can also Instantiate your main plugin file here
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('refered_customer', 'product'))) { // change birds with your post type
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,
'reviews_allowed' => 'open' === $post_object->comment_status,
));
$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);
}
/**
* Get the product type based on product ID.
*
* @since 3.0.0
* @param int $product_id
* @return bool|string
*/
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('refered_customer', 'product'))) { // change birds with your post type
return false;
} 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;
}
add_filter('woocommerce_product_get_price', 'woocommerce_product_get_price', 10, 2 );
function woocommerce_product_get_price( $invoice_price, $product ) {
if ($post->post->post_type === 'refered_customer') // change birds with your post type
$invoice_price = get_post_meta($post->id, "invoice_price", true);
return $invoice_price;
}
【问题讨论】:
标签: php wordpress woocommerce custom-post-type price