php - 在 Woocommerce 3 中以编程方式在可预订产品创建中添加人员类型

标签 php wordpress woocommerce product woocommerce-bookings

基本上,我正在尝试使用我制作的自定义表单在 Woocommerce 中添加新的可预订产品,因此我必须以编程方式添加产品。创建产品很好,问题是我无法弄清楚如何向我的产品添加新的人员类型,以便我可以固定多个价格。

有人知道怎么做吗?

这是我目前的代码。

$post_id = wp_insert_post( array(
    'post_title' => $_POST["title"],
    'post_content' => $_POST["description"],
    'post_status' => 'publish',
    'post_type' => "product",
) );
wp_set_object_terms( $post_id, 'booking', 'product_type' );

最佳答案

以下将启用“有人员”并为可预订产品创建您的人员类型:

// Create the product
$product_id = wp_insert_post( array(
    'post_title' => $_POST["title"],
    'post_content' => $_POST["description"],
    'post_status' => 'publish',
    'post_type' => "product",
) );

// Set the product type
wp_set_object_terms( $product_id, 'booking', 'product_type' );

// Get an instance of the WC_Product Object
$product = wc_get_product($product_id);

// Enable persons and save
$product->set_has_persons(true);
$product->save();

// Here define your person types (one array by person type)
$persons_type_data =  array(
    // First person type
    array( 
        'block_cost'  => 0,
        'cost'        => 16.50,
        'description' => '',
        'max'         => '',
        'min'         => '',
        'name'        => __('Adults'),
    ),
    // Second person type
    array(
        'block_cost'  => 0,
        'cost'        => 9.20,
        'description' => '',
        'max'         => '',
        'min'         => '',
        'name'        => __('Childs'),
    ),
);

// Loop Through persons type data
foreach( $persons_type_data as $key => $values ){
    $person_type = new WC_Product_Booking_Person_Type();
    $person_type->set_block_cost($values['block_cost']);
    $person_type->set_cost($values['cost']);
    $person_type->set_description($values['description']);
    $person_type->set_max($values['max']);
    $person_type->set_min($values['min']);
    $person_type->set_name($values['name']);
    $person_type->set_parent_id($product_id);
    $person_type->set_sort_order($key); // Sorting is based on the array order

    // Save the person type
    $person_type->save();

    // Add the person type to the array
    $persons[] = $person_type;
}
// Set person types and save the product
$product->set_person_types($persons);
$product->save();

经过测试并有效。

关于php - 在 Woocommerce 3 中以编程方式在可预订产品创建中添加人员类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52672216/

相关文章:

php - 我在 zend framework1 上提交表单时如何传递消息

regex - Wordpress 子目录上的不同项目

javascript - 在 woocommerce 商店中的第三个产品后插入一个 div

php - 是否可以扩展一个类而不扩展该类的方法?

php - 如何构建一个访问在线脚本的程序

php - MYSQL 连接查询不显示特定条件不起作用?

Javascript - 文本字段提交到弹出窗口

php - Wordpress:响应式地在前端静态页面上显示博客。

php - 仅在 WooCommerce 中自定义类型的管理产品上添加字段

php - WooCommerce Google Analytics(分析):在非标准成功页面上发送订单信息