skip to Main Content

I am trying to create a plugin for wordpress using woocommerce.
I create a class Product which will give me all the metadata concerning a product from woocommerce, but I can’t use woocommerce inside my functions:

<?php
class Product {
    //PROPERTIES
    public function __construct($sku) {
        $this->sku = $sku;
    }

    public function GetWooMeta($sku) {
        global $woocommerce;
        //Get product ID with SKU.
        $productID = $woocommerce->wc_get_product_id_by_sku( $sku );
        //Get Product object with ID.
        //$product_object = $woocommerce->wc_get_product( $productID );
        
        $product_meta = array();
        
        array_push($product_meta, 
        $woocommerce->$product_object->wp_get_attachment_image_url( $woocommerce>$product_object->get_image_id(), 'full' ),
        $woocommerce->$product_object->get_name(),
        $woocommerce->$product_object->get_price(), $woocommerce->get_permalink( $productID 
        ));
        return $product_meta;
    }
    $product1 = new Product ( 'GFI286260002I' );

    echo $product1->GetWooMeta( $product1->sku );
?>

This is the error thrown by wordpress:

//Fatal error: Uncaught Error: Call to a member function wc_get_product_id_by_sku() on null 

Thank you!

2

Answers


  1. Chosen as BEST ANSWER

    I was declaring my class outside of any functions and seems that wordpress didn't load Woocommerce first , which was the error.


  2. <?php
    class Product {
        //PROPERTIES
        public function __construct($sku) {
            $this->sku = $sku;
        }
    
        public function GetWooMeta($sku) {
            global $woocommerce;
            //Get product ID with SKU.
             $data_store = WC_Data_Store::load( 'product' );
             $productID = $data_store->get_product_id_by_sku( $sku );
            //$productID = $woocommerce->wc_get_product_id_by_sku( $sku );
            //Get Product object with ID.
            //$product_object = $woocommerce->wc_get_product( $productID );
            
            $product_meta = array();
            
            array_push($product_meta, 
            $woocommerce->$product_object->wp_get_attachment_image_url( $woocommerce>$product_object->get_image_id(), 'full' ),
            $woocommerce->$product_object->get_name(),
            $woocommerce->$product_object->get_price(), $woocommerce->get_permalink( $productID 
            ));
            return $product_meta;
        }
        //$product1 = new Product ( 'GFI286260002I' );
        $product = new WC_Product('GFI286260002I');
        $sku = $product->get_sku();
        echo $product1->GetWooMeta( $sku );
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search