Woocommerce fatal error: Uncaught Error: Call to a member function get_type() on string

Woocommerce fatal error: Uncaught Error: Call to a member function get_type() on string

我正在尝试构建一个插件,但当我认为它不应该存在时,我遇到了这个奇怪的致命错误。

add_action( 'wp_head', 'my_custom_plugin' );
function my_custom_plugin() {   
  global $product;
  if (is_product()) {
    $product_type = $product->get_type();
    if ($product_type =='variable') { 
        ...things happening here....
    }
  }
}

我的文件中也包含此代码require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');

谢谢:)

不确定到底发生了什么,但您可以试试这段代码,看看它是否适合您。它适用于我:

add_action( 'wp_head', 'my_custom_plugin' );

function my_custom_plugin() 
{   
  global $post;

  if (is_product()) {
    $product = wc_get_product($post->ID);
    $product_type = $product->get_type();
    if($product_type == 'variable'){ 
    // ...things happening here....
    }
  }
}

如果有效请告诉我!