如何在 woocommerce_after_main_content 中获取 WC_Product 对象

How to get the WC_Product object in woocommerce_after_main_content

我有一个函数可以在 WordPress 中的 main_content 操作挂钩之后输出文本,但是 Woocommerce 告诉我我有一个 CRITICAL Uncaught Error: Call to a member function get_id() on null in .../function.php.

我尝试传入 global $product,并检查它是否是 运行 函数之前的产品。该功能似乎工作正常,但我只是想摆脱致命错误。

有什么明显的我遗漏的东西吗?

这是我的函数:

add_action('woocommerce_after_main_content', 'display_prewired_notes');
    function display_prewired_notes() {
        global $product; //Tried global variable
        $product_id = $product->get_id(); //getting ID
        $product_name = $product->get_name(); //get name


        if (is_product() && has_term('prewired-pickguard', 'product_cat', $product_id)) { ?>

        //My HTML here
    
<?php
        }

        if (is_product() && $product_id == 6599) { ?>
    
        //More HTML for this specific product

<?php
        }
    };

编辑:

我已经根据@Martin 的建议尝试了一些方法,但仍然无法正常工作。

我试过:

1:

<?php

global $product


function display_prewired_notes($product) { // Pass it in

        $product_id = $product->get_id(); //getting ID
        $product_name = $product->get_name(); //get name

然后我得到 atal error: Uncaught Error: Call to a member function get_id() on string

2:

完全删除 global $product,我得到: Uncaught Error: Call to a member function get_id() on null

3:

删除 global $product 并保留 $product 作为参数:Fatal error: Uncaught Error: Call to a member function get_id() on string

钩子woocommerce_after_main_content主要用在2个WooCommerce模板中:

  • templates/archive-product.php (WooCommerce 归档页面)
  • templates/single-product.php (WooCommerce 单品页面)

因此您只能从单个产品页面获取WC_Product对象并且您需要定位第一个单个产品页面使用条件标签 is_product(),您可以通过这种方式获得 WC_product 对象:

add_action( 'woocommerce_after_main_content', 'display_prewired_notes' );
function display_prewired_notes() {
    // Targeting single product pages (before)
    if ( ! is_product() ) return; // exit

    global $product;
    
    // To be sure, If we don't get the product object
    if( ! is_a($product, 'WC_Product') ) {
        // Try to get an instance of the WC_Product object from Post id
        $product = wc_get_product( get_the_id() ); 
    }

    $product_name = $product->get_name(); //get product name

    if ( has_term(array('prewired-pickguard'), 'product_cat', $product->get_id() ) ) { 
        ?> 
        <!-- My HTML here -->
        <?php
    }

    if ( $product->get_id() == 6599 ) { 
        ?> 
        <!-- More HTML for this specific product -->
        <?php
    }
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。

On archive pages as it's a loop of products, it's not possible to get a product Id or/and the WC_Product Object…