Search code examples
phpwordpresstemplateswoocommerceproduct

Creating Product From Frontend using Page Template Seem To Work But No Product Is Created as Draft


I am trying once again to put together a page template that will do the following:

#1: Submit the product as a Draft #2: Send an email to the admin, asking for approval (change from draft to Publish) #3: After successful submit, redirect to "My account" page

All the fields are there, but no product shows up in WP-admin under Products. Can someone please find what's wrong?

This is the code:

Using child theme's functions file:

add_action( 'init', 'customer_creates_product_frontend' );
function customer_creates_product_frontend() {
    
        if ( isset( $_POST['submit_product'] ) && wp_verify_nonce( $_POST['product_nonce'], 'submit_product_form' ) ) {
            $errors = array();

            $product_title = sanitize_text_field( $_POST['product_title'] );
            if ( empty( $product_title ) ) {
                $errors[] = 'The title of the product is mandatory.';
            }

            $product_condition = sanitize_text_field( $_POST['product_condition'] );
            if ( empty( $product_condition ) ) {
                $errors[] = 'The condition of the product is mandatory.';
            }

            $starting_price = sanitize_text_field( $_POST['starting_price'] );
            if ( empty( $starting_price ) || ! is_numeric( $starting_price ) ) {
                $errors[] = 'A valid starting price of the product is mandatory.';
            }

            $reservation_price = sanitize_text_field( $_POST['reservation_price'] );
            if ( empty( $reservation_price ) || ! is_numeric( $reservation_price ) ) {
                $errors[] = 'The reserveration price of the product is mandatory.';
            }

            $increment_price = sanitize_text_field( $_POST['increment_price'] );
            if ( empty( $increment_price ) || ! is_numeric( $increment_price ) ) {
                $errors[] = 'The increment of how much each bid should increase the product price with is mandatory.';
            }

            $starting_sale_date = sanitize_text_field( $_POST['starting_sale_date'] );
            if ( empty( $starting_sale_date ) ) {
                $errors[] = 'Starting date for the product is mandatory.';
            }

            $end_sale_date = sanitize_text_field( $_POST['end_sale_date'] );
            if ( empty( $end_sale_date ) ) {
                $errors[] = 'End date for the product is mandatory.';
            }

            $buy_now_price = sanitize_text_field( $_POST['buy_now_price'] );
            if ( empty( $buy_now_price ) || ! is_numeric( $buy_now_price ) || $buy_now_price <= $starting_price) {
                $errors[] = 'A valid BUY NOW price for the product is mandatory, and it must be higher than the starting price.';
            }

            $short_description = sanitize_text_field( $_POST['short_description'] );
            if ( empty( $short_description ) ) {
                $errors[] = 'The short description for the product is mandatory.';
            }

            $long_description = sanitize_text_field( $_POST['long_description'] );
            if ( empty( $long_description ) ) {
                $errors[] = 'The long description for the product is mandatory.';
            }

            if ( empty( $errors ) ) {
                $new_product = wc_create_product( array (
                    'name' => $product_title,
                    'regular_price' => $starting_price,
                    'type' => 'auction', // set to "Auction" by the default - simple, grouped, externel, variable are also available
                    'description' => $short_description, // short desctiption
                    'short_description' => $long_description, // long description
                    'meta_input' => array (
                        'product_condition' => $product_condition,
                        'reservation_price' => $reservation_price,
                        'increment_price' => $increment_price,
                        'starting_sale_date' => date( 'Y-m-d \a\t H:i:s', strtotime( $starting_sale_date ) ),
                        'end_sale_date' => date( 'Y-m-d \a\t H:i:s', strtotime( $end_sale_date ) ),
                        'buy_now_price' => $buy_now_price,
                  )
             )
        );

                if ( is_wp_error( $new_product ) ) {
                    echo '<p class="text-danger">Error creating product. Please try again.</p>';
             
             } else {
     
        $the_customer = wp_get_current_user();
        $name_of_customer = $the_customer->get_billing_first_name();
        // send email to the admin with information about the request
        $admin_email = get_option( 'admin_email' );
        $subject = 'Approval Request from '.$name_of_customer.' who wants to publish '.$product_title.'';
        $message = 'The customer wants to publish '.$product_title.', with the following description: '.$short_description.'';
        wp_mail( $admin_email, $subject, $message );
    
    $new_product->set_status( 'draft' );
    wp_safe_redirect( home_url( '/mitt-konto/' ) );
        exit();
     
     }
     
       } else {
              
              foreach ( $errors as $error ) {
                    echo '<p class="text-danger">' . $error . '</p>';

          }
         }
    }
}

Using page template:

<?php
/**
* Template Name: Create Product
* @package Bootscore
*/
get_header();
?>
<div id="content" class="site-content">
<div id="primary" class="content-area">
<?php bs_after_primary(); ?>
<main id="main" class="site-main">
<div class="entry-content">
<br><br><br>

    <?php if ( is_user_logged_in() && in_array( 'administrator', wp_get_current_user()->roles ) ) { ?>

    <form method="post" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="product_title" class="form-label">Product Name</label>
            <input type="text" id="product_title" name="product_title" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="product_condition" class="form-label">Product Condition</label>
            <select id="product_condition" name="product_condition" class="form-select" required>
                <option value="new">New</option>
                <option value="old">Old</option>
            </select>
        </div>

        <div class="mb-3">
            <label for="starting_price" class="form-label">Starting Price</label>
            <input type="number" id="starting_price" name="starting_price" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="reservation_price" class="form-label">Reservation Price</label>
            <input type="number" id="reservation_price" name="reservation_price" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="increment_price" class="form-label">Increment Price</label>
            <input type="number" id="increment_price" name="increment_price" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="starting_sale_date" class="form-label">Starting Sale Date</label>
            <input type="datetime-local" id="starting_sale_date" name="starting_sale_date" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="end_sale_date" class="form-label">End Sale Date</label>
            <input type="datetime-local" id="end_sale_date" name="end_sale_date" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="buy_now_price" class="form-label">Buy Now Price</label>
            <input type="number" id="buy_now_price" name="buy_now_price" class="form-control" required>
        </div>

        <div class="mb-3">
            <label for="short_description" class="form-label">Short Description</label>
            <textarea id="short_description" name="short_description" class="form-control" required></textarea>
        </div>

        <div class="mb-3">
            <label for="long_description" class="form-label">Long Description</label>
            <textarea id="long_description" name="long_description" class="form-control" required></textarea>
        </div>

        <button type="submit" name="submit_product" class="btn btn-primary">Create Product</button>
        <?php wp_nonce_field( 'submit_product_form', 'product_nonce' ); ?>

    </form>

<?php } ?>
</div>
</main>
</div></div>
<?php get_footer();

Solution

  • Updated

    The function wc_create_product() doesn't exist… Since WooCommerce 3 you should use instead CRUD methods…

    I have tested the code with a simple product (from WC_Product_Simple class) and it works, so you will need to replace in the code below, the 2 WC_Product_Simple occurrences with the correct Product Auction class (something like WC_Product_Auction):

    add_action( 'init', 'customer_creates_product_frontend' );
    function customer_creates_product_frontend() { 
        $errors = array();
    
        if ( isset( $_POST['submit_product'] ) && wp_verify_nonce( $_POST['product_nonce'], 'submit_product_form' ) ) {
    
            $product_title = sanitize_text_field( $_POST['product_title'] );
            if ( empty( $product_title ) ) {
                $errors[] = 'The title of the product is mandatory.';
            }
    
            $product_condition = sanitize_text_field( $_POST['product_condition'] );
            if ( empty( $product_condition ) ) {
                $errors[] = 'The condition of the product is mandatory.';
            }
    
            $starting_price = sanitize_text_field( $_POST['starting_price'] );
            if ( empty( $starting_price ) || ! is_numeric( $starting_price ) ) {
                $errors[] = 'A valid starting price of the product is mandatory.';
            }
    
            $reservation_price = sanitize_text_field( $_POST['reservation_price'] );
            if ( empty( $reservation_price ) || ! is_numeric( $reservation_price ) ) {
                $errors[] = 'The reserveration price of the product is mandatory.';
            }
    
            $increment_price = sanitize_text_field( $_POST['increment_price'] );
            if ( empty( $increment_price ) || ! is_numeric( $increment_price ) ) {
                $errors[] = 'The increment of how much each bid should increase the product price with is mandatory.';
            }
    
            $starting_sale_date = sanitize_text_field( $_POST['starting_sale_date'] );
            if ( empty( $starting_sale_date ) ) {
                $errors[] = 'Starting date for the product is mandatory.';
            }
    
            $end_sale_date = sanitize_text_field( $_POST['end_sale_date'] );
            if ( empty( $end_sale_date ) ) {
                $errors[] = 'End date for the product is mandatory.';
            }
    
            $buy_now_price = sanitize_text_field( $_POST['buy_now_price'] );
            if ( empty( $buy_now_price ) || ! is_numeric( $buy_now_price ) || $buy_now_price <= $starting_price) {
                $errors[] = 'A valid BUY NOW price for the product is mandatory, and it must be higher than the starting price.';
            }
    
            $short_description = sanitize_text_field( $_POST['short_description'] );
            if ( empty( $short_description ) ) {
                $errors[] = 'The short description for the product is mandatory.';
            }
    
            $long_description = sanitize_text_field( $_POST['long_description'] );
            if ( empty( $long_description ) ) {
                $errors[] = 'The long description for the product is mandatory.';
            }
    
            if ( count($errors) == 0 && class_exists('WC_Product_Simple') ) {
                $product = new WC_Product_Simple(); // Create an empty product object (type "auction")
                $product->set_name($product_title);
                $product->set_regular_price($starting_price);
                $product->set_price($starting_price);
                $product->set_short_description($short_description);
                $product->set_description($long_description);
                $product->add_meta_data('product_condition', $product_condition, true);
                $product->add_meta_data('reservation_price', $reservation_price, true);
                $product->add_meta_data('increment_price', $increment_price, true);
                $product->add_meta_data('starting_sale_date', date( 'Y-m-d \a\t H:i:s', strtotime( $starting_sale_date ) ), true);
                $product->add_meta_data('end_sale_date', date( 'Y-m-d \a\t H:i:s', strtotime( $end_sale_date ) ), true);
                $product->add_meta_data('buy_now_price', $buy_now_price, true);
                $product->set_status('draft');
                $product_id = $product->save();
            }
    
            if ( ! $product_id ) {
                echo '<p class="text-danger">Error creating product. Please try again.</p>';
            } else {
                global $current_user;
    
                $first_name  = $current_user->billing_first_name;
                $admin_email = get_option( 'admin_email' );
                $subject     = 'Approval Request from '.$first_name.' who wants to publish '.$product_title.'';
                $message     = 'The customer wants to publish '.$product_title.', with the following short description: '.$short_description.'';
                
                // Send email to the admin with information about the request
                wp_mail( $admin_email, $subject, $message );
                // Redirect User to My account
                wp_safe_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
                exit();
            }
        } elseif ( count($errors) > 0 ) {
            foreach ( $errors as $error ) {
                echo '<p class="text-danger">' . $error . '</p>';
            }
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and work.

    The template File:

    /**
     * The template for displaying in frontend the product Auction creation form.
     *
     * Template name: Create Product
     *
     * @package Bootscore
     */
    
    global $current_user;
    
    get_header(); ?>
    
    <div id="content" class="site-content">
    <div id="primary" class="content-area">
    <main id="main" class="site-main">
    <div class="entry-content">
    <br><br><br>
    
        <?php if ( is_a($current_user, 'WP_User') && in_array( 'administrator', $current_user->roles ) ) { ?>
    
        <form method="post" enctype="multipart/form-data">
            <div class="mb-3">
                <label for="product_title" class="form-label"><?php _e('Product Name'); ?></label>
                <input type="text" id="product_title" name="product_title" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="product_condition" class="form-label"><?php _e('Product Condition'); ?></label>
                <select id="product_condition" name="product_condition" class="form-select" required>
                    <option value="new"><?php _e('New'); ?></option>
                    <option value="old"><?php _e('Old'); ?></option>
                </select>
            </div>
    
            <div class="mb-3">
                <label for="starting_price" class="form-label"><?php _e('Starting Price'); ?></label>
                <input type="number" id="starting_price" name="starting_price" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="reservation_price" class="form-label"><?php _e('Reservation Price'); ?></label>
                <input type="number" id="reservation_price" name="reservation_price" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="increment_price" class="form-label"><?php _e('Increment Price'); ?></label>
                <input type="number" id="increment_price" name="increment_price" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="starting_sale_date" class="form-label"><?php _e('Starting Sale Date'); ?></label>
                <input type="datetime-local" id="starting_sale_date" name="starting_sale_date" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="end_sale_date" class="form-label"><?php _e('End Sale Date'); ?></label>
                <input type="datetime-local" id="end_sale_date" name="end_sale_date" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="buy_now_price" class="form-label"><?php _e('Buy Now Price'); ?></label>
                <input type="number" id="buy_now_price" name="buy_now_price" class="form-control" required>
            </div>
    
            <div class="mb-3">
                <label for="short_description" class="form-label"><?php _e('Short Description'); ?></label>
                <textarea id="short_description" name="short_description" class="form-control" required></textarea>
            </div>
    
            <div class="mb-3">
                <label for="long_description" class="form-label"><?php _e('Long Description'); ?></label>
                <textarea id="long_description" name="long_description" class="form-control" required></textarea>
            </div>
    
            <button type="submit" name="submit_product" class="btn btn-primary"><?php _e('Create Product'); ?></button>
            <?php wp_nonce_field( 'submit_product_form', 'product_nonce' ); ?>
    
        </form>
    
    <?php } ?>
    </div>
    </main>
    </div>
    </div>
    <?php
    get_footer();
    

    Related: Create programmatically a product using CRUD methods in Woocommerce 3