How to add Woocommerce function namespaces in controllers

Hi sagers,

I’m using woocommerce-functions in my controllers, e.g. wc_logout_url() and many more like so:

  public function logoutLink()
  {
    if (is_user_logged_in()) {
      return [
        'label' => __('Logout', 'woocommerce'),
        'icon' => '',
        'url' => wc_logout_url(),
      ];
    }
    return;
  }

This works. However, my IDE (VS Code with Inteliphense) shows me “undefined function”-errors when using woocommerce-functions in controllers:

It actually doesn’t cause any problems, it just annoys me, because there are technically no errors.

I know I probably just need to add the correct namespace, but I can’t find out which one I need to add in order to get my IDE to recognize the woocommerce functions. I tried WC, WooCommerce and several more.

Any help is much appreciated.

You scope your controller file to a namespace (namespace App\Controllers;) I strongly assume:

By default, wc_logout_url() is then relative to that namespace (which is incorrect as the WooCommerce related functions and such aren’t in namespace App\Controllers).
You can actually see this in the IDE Intelephense hint: Undefined function App\Controllers\wc_logout_url.

You can prefix global non-namespaced functions with a \ to resolve them without the namespace:

\wc_logout_url();

Thanks for your response. I’m aware of the controller documentation.
Prefixing the functions with \ was also a thing I already tried. No success though, same issue.

But - shame on me - I might have asked my question wrong or incompletely.

I’m running my wordpress inside a docker-container and mount my theme into it via volumes. In my IDE I’m only working in the theme-directory itself and therefor the woocommerce-plugin-files are just not present in my theme-directory and the IDE really doesn’t know anything about a thing called woocommerce.

I wonder what would be the best solution (if there’s any) to make my IDE aware of woocommerce without the need of having the complete wordress-files in my project structure.

So I use VSCode currently as IDE and I add the whole project directory, including plugins/ and themes/. This makes the IDE scan everything. You may mount only your themes into the Docker container - but your IDE doesn’t have to be restricted like that.
Edit: Also for development you may simply also mount the plugins/ and themes/ folders from your workstation into the Docker container, so both systems have the exact same files. Are you using a Bedrock site?

Another alternative that may work but I find not very good is to add an IDE extension that adds autocomplete/snippet support for WooCommerce, like WooCommerce - Snippets & autocomplete - Visual Studio Marketplace.
But letting the IDE discover the actual code is much more preferable.

1 Like

Ok, yeah, that worked. I now have all the plugins in my project folder and mount them into the container via volumes. Thanks :+1: