0

I am trying to add WooCommerce products through my own plugin. My form is displayed, but when I submit it, then an error is thrown.

This is my form which is displayed:

This is my form in WordPress

After submitting above form error below is coming (details of the error):

This image has details of error

This is my code:

/**
  *Plugin Name: Product Form
  *Description: This my First Plugin
 **/

require __DIR__ . '/../vendor/autoload.php';

use Automattic\WooCommerce\Client;
use Automattic\WooCommerce\HttpClient\HttpClientException;
$woocommerce = new Client(
    'http://httpsjaymodi873626907wordpresscom.local/',
    'my ck',
    'my cs',
    [
        'wp_api' => true,
        'version' => 'wc/v3',
        'verify_ssl' => 'false'
    ]
);

<?php
    function product_form_menu_option()
    {
        add_menu_page('Form', 'Product Form', 'manage_options', 'product_form_menu', 'product_form_page', '', 200);
    }

    add_action('admin_menu', 'product_form_menu_option');

    function product_form_page()
    {
        ?>
            <h1>Product Form</h1>
            <form action="" method="post">
                <label>Product Name</label>
                <input type="text" name="name" required=""><br><br>
                <label>Price</label>
                <input type="text" name="regular_price"><br><br>
                <label>Description</label>
                <input type="text" name="description" required=""><br><br>
                <label>Short Description</label>
                <input type="text" name="short_description"><br><br><br>
                <button type="submit" name="submit">Submit</button>
            </form>
        <?php
    }

    if(isset($_POST['submit']))
    {
        addProduct();
    }

    function addProduct()
    {
        echo $_POST['name'];
        $data = [
                'name' => $_POST['name'],
                'type' => $_POST['regular_price'],
                'regular_price' => $_POST['regular_price'],
                'description' => $_POST['description'],
                'short_description' => $_POST['short_description'],
                ];

        print_r($woocommerce->post('products', $data));
    }

?>
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Jay Modi
  • 1
  • 1

1 Answers1

0

it seems like your <?php open tag should be on the first line. the error basically says the $woocommerce variable is null.

Also, it would probably make sense to initialize that variable inside the relevant function, or you are likely to have scope visibility problems

Lauri P
  • 178
  • 2
  • 10