按产品名称获取woocommerce产品ID

时间:2017-05-18 23:00:40

标签: php wordpress woocommerce

我正在开发自定义功能,以便在用户点击帖子联系表单上的按钮时以编程方式创建一个woocommerce产品。以下是我用于创建产品的代码,但我仍然坚持通过代码将此产品添加到购物车,因为我无法在功能代码中获得产品ID。需要你的帮助告诉我如何获得产品ID以将其添加到购物车。

    function contactform7_before_send_mail( $tour_to_product ) {

    $tour_to_product = WPCF7_Submission::get_instance();

    if ( $tour_to_product ) {
    $formData = $tour_to_product->get_posted_data();
    }

        $tourprice =$formData['tour-price'];
        $tourdiscountprice =$formData['tour-discount-price'];
        $tourname =$formData['tour-name'];
        $noadults =$formData['no-adult'];
        $nochild =$formData['no-child'];
        if(!empty($formData['tour-discount-price'])) 
        {
            $finalprice =$formData['tour-discount-price'];
        } else {
            $finalprice =$formData['tour-price']; 
        }

    $post = array(
        'post_author' => $user_id,
        'post_content' => '',
        'post_status' => "publish",
        'post_title' => $tourname,
        'post_parent' => '',
        'post_type' => "product",
    );

    //Create post
    $post_id = wp_insert_post( $post, $wp_error );
    if($post_id){
        global $tour_id;
        $attach_id = get_post_meta($product->parent_id, "_thumbnail_id", true);
        add_post_meta($post_id, '_thumbnail_id', $attach_id);
// i am trying here to get the product id
        $tour_id = get_post_meta($product->id());
    }

    wp_set_object_terms( $post_id, 'Tours', 'product_cat' );
    wp_set_object_terms( $post_id, 'simple', 'product_type');

    update_post_meta( $post_id, '_visibility', 'visible' );
    update_post_meta( $post_id, '_stock_status', 'instock');
    update_post_meta( $post_id, 'total_sales', '0');
    update_post_meta( $post_id, '_downloadable', 'no');
    update_post_meta( $post_id, '_virtual', 'yes');
    update_post_meta( $post_id, '_regular_price', $tourprice );
    update_post_meta( $post_id, '_sale_price', $tourdiscountprice );
    update_post_meta( $post_id, '_purchase_note', "" );
    update_post_meta( $post_id, '_featured', "no" );
    update_post_meta( $post_id, '_sku', "");
    update_post_meta( $post_id, '_product_attributes', array());
    update_post_meta( $post_id, '_sale_price_dates_from', "" );
    update_post_meta( $post_id, '_sale_price_dates_to', "" );
    update_post_meta( $post_id, '_price', $tourprice );
    update_post_meta( $post_id, '_sold_individually', "" );
    update_post_meta( $post_id, '_manage_stock', "no" );
    update_post_meta( $post_id, '_backorders', "no" );
    update_post_meta( $post_id, '_stock', "" );
    // i am trying to output the product id for testing    
    echo "<script type='text/javascript'>alert('$tour_id')</script>";

    }

    remove_all_filters ('wpcf7_before_send_mail');
    add_action( 'wpcf7_before_send_mail', 'contactform7_before_send_mail' );

1 个答案:

答案 0 :(得分:0)

那是对的。下面的代码行包含最后添加的帖子的ID。

$post_id = wp_insert_post( $post, $wp_error ); //<== ID