Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

wordpress - How to use woocommerce classes from a custom plugin that uses composer autoload

Im using Composer autoload in my plugin to make it easier to manage all the files and classes instead of writing everysingle time require_once

However Im having trouble trying to access native woocommerce classes. My classes are defined with namespaces as for example:

<?php
namespace IncApi;

class RestClientApi
{
....
}

If I try to call a woocommerce class within this class for example:

<?php
namespace IncApi;

class RestClientApi
{

  public $example = new WC_product();

}

I get the error Class Inc/Api/WC_product not found I know what the error means, but I don't have idea how to use Woocommerce classes from my custom plugin, considering I'm using autoload and namespaces in my custom plugin classes.

UPDATE As requested I added my autoload configuration, it is pretty simple, Im just calling my /inc folder

"autoload": {
        "psr-4": {"Inc": "./inc"}
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your plugin composer.json, add something like this (you adapt it to your needs):

    "autoload": {
        "psr-4": {
            "WooCommerceNamespace":"path/to/woocomerce/classes/folder"
        }
    },

Then run a

composer dump-autoload 

inside the composer.json folder.

Then add to your plugin file: use WooCommerceNamespaceWC and the WC class should now be available.

(if your WC.php file already has a namespace declaration, use that namespace in your psr-4 declaration).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...