Как создать продукт WooCommerce из отправки формы веб-интерфейса с проверкой формы - PullRequest
0 голосов
/ 17 января 2019

Требуется помощь: я пытаюсь создать форму, которая будет публиковать продукт wooCommerce из внешнего интерфейса после выполнения этого вопроса ( Добавить временный продукт Woocommerce ). Проблема, с которой я сталкиваюсь сейчас, заключается в том, что каждый раз, когда я отправляю форму, я получаю эту ошибку (если я не проверяю форму) Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\WOOstores\wp-includes\class.wp-styles.php:225) in C:\xampp\htdocs\WOOstores\wp-includes\pluggable.php on line 1219. Я действительно хотел бы проверить форму перед отправкой, и все, что я пытался, выбрасывает ошибку, связанную с WP_Error() ниже, это ошибка, которую я получаю, когда пытаюсь проверить поля формы;

Warning: A non-numeric value encountered in C:\xampp\htdocs\WOOstores\wp-content\themes\adrianstores\woocommerce\myaccount\custom-orders.php on line 73 // Will indicate this line in my below code

Notice: Object of class WP_Error could not be converted to int in C:\xampp\htdocs\WOOstores\wp-includes\taxonomy.php on line 2297

Notice: Object of class WP_Error could not be converted to int in C:\xampp\htdocs\WOOstores\wp-includes\taxonomy.php on line 2297

Notice: Object of class WP_Error could not be converted to int in C:\xampp\htdocs\WOOstores\wp-includes\functions.php on line 3843

Продукт создается без проблем, как именно он должен работать (если я не проверяю поле), но я действительно хочу проверить форму, но у меня проблемы с этим. Ниже приведен полный код

<form method="post" action="">
    <div class="form-group">
        <div class="co-message"></div> <!--I want the validation message to show up here. Error & Success Validation-->
        <label for="co_currency"><?php _e('Select Currency', 'text-domain'); ?></label>
        <select class="form-control" id="co_currency" name="co_currency">
        <option value="USD">USD</option>
        <option value="RMB">RMB</option>
        </select>
    </div>
    <div id="is_amazon" class="form-group is_amazon">
        <label class="disInBlk" for="co_isAmazon"><?php _e('Is this an Amazon Product?','text-domain').':'; ?></label>
        <input type="checkbox" name="co_isAmazon" id="co-isAmazon">
            </div>
    <div class="form-group">
        <label for="co_productTitle"><?php _e('Product Name/Title','text-domain').':'; ?></label>
        <input type="text" name="co_productTitle" class="form-control" id="co-productTitle" value="">
    </div>
    <div class="form-group">
        <label for="co_productLink"><?php _e('Product Link','text-domain').':'; ?></label>
        <input type="url" name="co_productLink" class="form-control" id="co-productLink" value="" placeholder="<?php _e('http://...', 'text-domain'); ?>">
    </div>
    <div class="form-group">
        <label for="co_productPriceUSD"><?php _e('Product Price (USD)','text-domain').':'; ?></label>
        <input type="number" name="co_productPriceUSD" class="form-control" id="co-productPriceUSD" value="0" step="0.01">
    </div>
    <div class="form-group">
        <label for="co_productPriceNGN"><?php _e('Price Converted to NGN','text-domain').':'; ?></label>
        <input type="number" name="co_productPriceNGN" class="form-control" id="co-productPriceNGN" value="0" readonly>
    </div>
    <div class="form-group">
        <label for="co_productWeightKG"><?php _e('Weight (in KG)','text-domain').':'; ?></label>
        <input type="number" name="co_productWeightKG" class="form-control" id="co-productWeightKG" value="" step="0.01">
    </div>
    <div class="form-group-btn">
        <input type="submit" name="co_submit" class="form-control" id="co-submit" value="<?php echo _e('Place Your Order', 'text-domain'); ?>">
        <input type="hidden" name="amountNGNUpdated" value="<?php echo $ExhangeRateUSD; ?>" id="CurrencyEX">
        <input type="hidden" name="productCategoryUpdate" value="<?php echo $product_CO_terms; ?>">
    </div>
</form>

PHP CODE, который находится на той же странице, что и форма HTML

function get_product_category_by_id( $category_id ) {
    $term = get_term_by( 'id', $category_id, 'product_cat', 'ARRAY_A' );
    return $term['name'];
}
$product_CO_terms = get_product_category_by_id( 15 );

$ProductTitle = $ProductURL = $ProductPriceValue = $ProductWeight = $ExchangeRate = "";
$errorpTitle = $errorpUrl= $errorpPrice = $errorpWeight = "";

if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {

$ExchangeRate       = test_input($_POST['amountNGNUpdated']);
$ProductCategory    = test_input($_POST['productCategoryUpdate']);

$ProductTitle = test_input($_POST['co_productTitle']);
$ProductURL = test_input($_POST['co_productLink']);
$ProductPriceValue  = test_input($_POST['co_productPriceUSD']);
$ProductWeight  = test_input($_POST['co_productWeightKG']);


/* THIS IS THE VALIDATION I DID, Which i dont know why it giving me the WP_Error() error
if ( empty($ProductTitle) ) {
    $errorpTitle = __('Product Title is required. e.g. iPhone XS Max 16GB Silver', 'text-domain');
} else {
    $ProductTitle = test_input($_POST['co_productTitle']);
}

if ( empty($ProductURL) ) {
    $errorpUrl = __('Product URL is required. e.g. http://amazon.com/.../', 'text-domain');
} else {
    $ProductURL = test_input($_POST['co_productLink']);
}

if ( empty($ProductPriceValue) || $ProductPriceValue == 0 ) {
    $errorpPrice = __('Product Price is required.', 'text-domain');
} else {
    $ProductPriceValue  = test_input($_POST['co_productPriceUSD']);
}

if ( empty($ProductWeight) ) {
    $errorpWeight = __('Product Weight is required. Weight unit should be in KG. You can use the Weight converter to convert your weight from lbs to kg.', 'text-domain');
} else {
    $ProductWeight  = test_input($_POST['co_productWeightKG']);
}*/

$NewProductPrice = $ProductPriceValue * $ExchangeRate; //This is the line 73 in which i was getting "A non-numeric value encountered"

//add them in an array
$post = array(
    'post_status' => "publish",
    'post_title' => $ProductTitle,
    'post_type' => "product",
);

//create product for product ID
$product_id = wp_insert_post( $post, __('Cannot create product', 'izzycart-function-code') );

//type of product
wp_set_object_terms($product_id, 'simple', 'product_type');

//Which Category
wp_set_object_terms( $product_id, $product_CO_terms, 'product_cat' );

//add product meta
update_post_meta( $product_id, '_regular_price', $NewProductPrice );
update_post_meta( $product_id, '_price', $NewProductPrice );
update_post_meta( $product_id, '_weight', $ProductWeight );
update_post_meta( $product_id, '_store_product_uri', $ProductURL );
update_post_meta( $product_id, '_visibility', 'visible' );
update_post_meta( $product_id, '_stock_status', 'instock' );

//Add product to Cart
return WC()->cart->add_to_cart( $product_id ); 

Чего я хотел бы достичь с помощью приведенной выше строки return WC()->cart->add_to_cart( $product_id );, так это добавить товар в корзину и перенаправить в корзину. (используя return, я получаю пустую страницу, но добавляю продукт для получения, что делает эту строку не лучшим подходом)

ПОМОГИТЕ, ЧТО НУЖНО;
1. Как заставить форму проверить поле. Если какое-либо поле пусто, оно должно выдать сообщение об ошибке в верхней части формы. Там, где у нас есть <div class="co-message"></div>, и если все поле проходит проверку, оно должно выдать сообщение об успешном завершении и приступить к созданию продукта.
2. После создания товара он должен добавить товар в корзину и перенаправить в корзину.

Спасибо

1 Ответ

0 голосов
/ 18 января 2019

Я смог проверить форму и создать продукт, если бы я хотел, чтобы он работал. Просто если кто-то столкнется с подобной проблемой и захочет получить ответ на этот вопрос.

КОД PHP:

$ProductTitle = $ProductURL = $ProductPriceValue = $ProductShippingFee = $ProductWeight = "";
$error_pTitle = $error_pLink = $error_pPrice = $error_pShipping = $error_pweight = $success_call = "";
$productPrice_converted = "";
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_REQUEST['co_submit']) ) {
$ExchangeRate       = test_input($_POST['amountNGNUpdated']);
$ProductCategory    = test_input($_POST['productCategoryUpdate']);

//Validate Product Title
if( empty( test_input($_POST['co_productTitle']) ) ) {
    $error_pTitle = __('Product Title is required.', 'izzycart-function-code');
} else {
    $ProductTitle = test_input($_POST['co_productTitle']);
}

//Validate Product URL
if( empty( test_input($_POST['co_productLink']) ) ) { 
    $error_pLink = __('Product Link is required.', 'izzycart-function-code');
} elseif ( !preg_match("@^https?://@", test_input($_POST['co_productLink']) ) ) {
    $error_pLink = __('Please enter a url that starts with http:// or https://', 'izzycart-function-code');
} elseif ( isset($_POST['co_isAmazon']) == 1 && strpos($_POST['co_productLink'], 'amazon') === false ) {
    $error_pLink = __('This is not an Amazon product. Please enter a valid amazon product.', 'izzycart-function-code');
} else {
    $ProductURL = test_input($_POST['co_productLink']);
}

//Validate Product Price
if( empty( test_input($_POST['co_productPriceUSD']) ) || test_input($_POST['co_productPriceUSD']) == 0 ) { 
    $error_pPrice = __('Product Price is required.', 'izzycart-function-code');
} else {
    $ProductPriceValue = test_input($_POST['co_productPriceUSD']);
}

//Validate Product Shipping
if( empty( test_input($_POST['co_productShippingFee']) ) ) { 
    $error_pShipping = __('Product Shipping fee is required.', 'izzycart-function-code');
} else {
    $ProductShippingFee = test_input($_POST['co_productShippingFee']);
}

//Validate Product Weight
if( empty( test_input($_POST['co_productWeightKG']) ) || test_input($_POST['co_productWeightKG']) == 0 ) { 
    $error_pweight = __('Product Weight is required. Weight are in KG, use the weight converter to covert your lbs item to KG', 'izzycart-function-code');
} else {
    $ProductWeight  = round(test_input($_POST['co_productWeightKG']), 2);
}

if ($ProductPriceValue && $ExchangeRate ) {
    $productPrice_converted = $ProductPriceValue * $ExchangeRate;
}

//No Errors Found
if ( $error_pTitle == "" && $error_pLink == "" && $error_pPrice == "" && $error_pShipping = "" $error_pweight == "" ) {
    //add them in an array
    $post = array(
        'post_status' => "publish",
        'post_title' => $ProductTitle,
        'post_type' => "product",
    );

    //create product for product ID
    $product_id = wp_insert_post( $post, __('Cannot create product', 'izzycart-function-code') );

    //type of product
    wp_set_object_terms($product_id, 'simple', 'product_type');

    //Which Category
    wp_set_object_terms( $product_id, $product_CO_terms, 'product_cat' );

    //add product meta
    update_post_meta( $product_id, '_regular_price', $productPrice_converted );
    update_post_meta( $product_id, '_price', $productPrice_converted );
    update_post_meta( $product_id, '_weight', $ProductWeight );
    update_post_meta( $product_id, '_store_product_uri', $ProductURL );
    update_post_meta( $product_id, '_visibility', 'visible' );
    update_post_meta( $product_id, '_stock_status', 'instock' );

    //Add Product To cart
    $found = false;
    if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if ( $_product->get_id() == $product_id )
                $found = true;
        }
        // if product not found, add it
        if ( ! $found )
            WC()->cart->add_to_cart( $product_id );
    } else {
        // if no products in cart, add it
        WC()->cart->add_to_cart( $product_id );
    }

//Sending Mail to Admin 
    //I installed an application hMailServer on my PC, because i was working on a local
    //server (XAMPP) and it wont send out mail(), so i wasn't getting the success message
    //as soon as i installed the application.. the mail() function worked and i get the success message
    //and product is added to cart. Though didn't receive the mail in my inbox for reason i don't know but i 
    //will update this answer to confirm that the sending mail works. but the fact that i got the success message. it will work on a LIVE server
    $message_bd = '';
    unset($_POST['co_submit']);

    foreach ($_POST as $key => $value) {
        $message_bd .= "$key: $value\n";
    }

    $to = $AdminEmailFor_CO; //This is a custom field i created which stores the admin email in the database and can be changed from wordpress dashboard (you can write directly your admin email)
    $subject = $SubjectFor_CO; // Same as the subject. They are stored the in options table
    $header = 'From: webmaster@example.com' . "\r\n" .
                'Reply-To: webmaster@example.com' . "\r\n" .
                'X-Mailer: PHP/' . phpversion();
    if ( mail($to, $subject, $message_bd ) ) {
        //Success Message & reset Fields 
        $success_call = sprintf(__('Success: Product has been added to your cart. Click the view cart button below to proceed with your custom order. <a href="%s">View Cart</a>', 'izzycart-function-code'), wc_get_cart_url() );
        $ProductTitle = $ProductURL = $ProductPriceValue = $ProductWeight = "";
        $productPrice_converted = 0;
    }
  }
}
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

HTML ФОРМА обновлена ​​до следующей

<form method="post" action="">
    <div class="co-success"><?= $success_call ?></div>
    <div class="form-group">
        <label for="co_currency"><?php _e('Select Currency', 'izzycart-function-code'); ?></label>
        <select class="form-control" id="co_currency" name="co_currency">
          <option value="USD">USD</option>
          <option value="RMB">RMB</option>
        </select>
    </div>
    <div id="is_amazon" class="form-group is_amazon">
        <label class="disInBlk" for="co_isAmazon"><?php _e('Is this an Amazon Product?','izzycart-function-code').':'; ?></label>
        <input type="checkbox" name="co_isAmazon" id="co-isAmazon" <?php echo (isset($_POST['co_isAmazon'])?'checked="checked"':'') ?>>
    </div>
    <div class="form-group">
        <label for="co_productTitle"><?php _e('Product Name/Title','izzycart-function-code').':'; ?></label>
        <input type="text" name="co_productTitle" class="form-control" id="co-productTitle" value="<?= $ProductTitle ?>">
        <div class="co-error"><?php echo $error_pTitle ?></div>
    </div>
    <div class="form-group">
        <label for="co_productLink"><?php _e('Product Link','izzycart-function-code').':'; ?></label>
        <input type="text" name="co_productLink" class="form-control" id="co-productLink" value="<?= $ProductURL ?>" placeholder="<?php _e('http://...', 'izzycart-function-code'); ?>">
        <div class="co-error"><?php echo $error_pLink ?></div>
    </div>
    <div class="form-group">
        <label for="co_productPriceUSD"><?php _e('Product Price (USD)','izzycart-function-code').':'; ?></label>
        <input type="number" name="co_productPriceUSD" class="form-control" id="co-productPriceUSD" value="<?= $ProductPriceValue ?>" step="0.01">
        <div class="co-error"><?php echo $error_pPrice ?></div>
    </div>
    <div class="form-group">
        <label for="co_productShippingFee"><?php _e('Shipping Fee of Product/Item','izzycart-function-code').':'; ?></label>
        <div class="co-desc"><?php echo __('N.B: If the product is FREE shipping from the store you\'re buying from, enter 0 as the shipping fee.', 'izzycart-function-code'); ?></div>
        <input type="number" name="co_productShippingFee" class="form-control" id="co_productShippingFee" value="<?= $ProductShippingFee ?>" step="0.01">
        <div class="co-error"><?php echo $error_pShipping ?></div>
    </div>
    <div class="form-group">
        <label for="co_productPriceNGN"><?php _e('Product Price Converted to NGN','izzycart-function-code').':'; ?></label>
        <input type="number" name="co_productPriceNGN" class="form-control" id="co-productPriceNGN" value="<?= $productPrice_converted ?>" readonly>
    </div>
    <div class="form-group">
        <label for="co_productWeightKG"><?php _e('Weight (in KG)','izzycart-function-code').':'; ?></label>
        <input type="number" name="co_productWeightKG" class="form-control" id="co-productWeightKG" value="<?= $ProductWeight ?>" step="0.001">
        <div class="co-error"><?php echo $error_pweight ?></div>
    </div>
    <div class="form-group-btn">
        <input type="submit" name="co_submit" class="form-control" id="co-submit" value="<?php echo _e('Place Your Order', 'izzycart-function-code'); ?>">
        <input type="hidden" name="amountNGNUpdated" value="<?php echo $ExhangeRateUSD; ?>" id="CurrencyEX">
        <input type="hidden" name="productCategoryUpdate" value="<?php echo $product_CO_terms; ?>">
    </div>
</form>

Результат выглядит так

create a woocommerce product from frontend

показывая подтверждение

create a woocommerce product from frontend with validation

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...