You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce技术问题:如何获取商品作者的邮箱地址?

Troubleshooting WooCommerce Product Author Email Retrieval

Hey there! Let's figure out why your code isn't pulling the product author's email properly. Here are some common issues and fixes to get this working:

Common Issues with Your Current Code

  • Uninitialized $product variable: In some contexts (like custom templates, archive pages, or outside the single product loop), the global $product might not be set or properly instantiated. Directly accessing $product->post can fail if $product isn't a valid WC_Product object.
  • Direct object property access: WooCommerce recommends using official methods instead of directly accessing $product->post to avoid compatibility issues across versions.

Fixed Code Examples

For Single Product Pages (or where global $post is available)

// Ensure we have a valid WC_Product object
global $product;
if ( ! $product instanceof WC_Product ) {
    $product = wc_get_product( get_the_ID() );
}

// Get the product author's ID safely
$author_id = get_post_field( 'post_author', $product->get_id() );

// Retrieve the author's email (use 'user_email' for official compliance)
$author_email = get_the_author_meta( 'user_email', $author_id );

// Output or return the email (sanitize for safety!)
echo esc_attr( $author_email );
// Or return it if used in a function: return esc_attr( $author_email );

For Product Loops (e.g., Archive Pages)

If you're working in a loop (like a shop page), make sure to fetch the product object for each item:

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        
        $product = wc_get_product( get_the_ID() );
        if ( $product ) {
            $author_id = get_post_field( 'post_author', $product->get_id() );
            $author_email = get_the_author_meta( 'user_email', $author_id );
            
            // Safely display the email
            echo '<div class="product-author-email">' . esc_attr( $author_email ) . '</div>';
        }
    }
}

Key Notes

  • Always validate that $product is a valid WC_Product instance before accessing its properties/methods.
  • Using get_post_field() to fetch the author ID is more reliable than direct property access, as it works even if the product object's internal structure changes.
  • Sanitize the output with esc_attr() to prevent XSS vulnerabilities when displaying the email publicly.

内容的提问来源于stack exchange,提问作者Joe Bloggs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:42:08