自定义WooCommerce产品页面(single-product.php)无法获取产品ID
解决WooCommerce自定义single-product.php中无法获取产品ID的问题
你代码里无法获取产品ID的核心原因是全局$product对象未被正确初始化——在自定义模板中,WooCommerce不会自动保证该全局变量可用。以下是两种可行的解决方式:
方式1:直接通过文章对象获取ID
产品在WordPress中属于自定义文章类型,可直接用get_the_ID()函数或$post->ID获取ID,无需依赖WooCommerce的$product对象:
<h1><?php echo esc_attr( get_the_ID() ); ?></h1>
方式2:手动初始化WooCommerce产品对象
如果需要调用WooCommerce产品类的其他方法(比如获取价格、库存状态等),可以通过wc_get_product()手动实例化产品对象:
<?php global $post; $product = wc_get_product( $post->ID ); ?> <h1><?php echo esc_attr( $product->get_id() ); ?></h1>
修改后的完整代码
同时建议把表单里的硬编码链接和产品ID改成动态值,避免换产品后失效:
<?php get_header(); do_action( 'woocommerce_before_main_content' ); the_title( '<h2 class="product_title entry-title"></h2>' ); global $post; // 初始化产品对象 $product = wc_get_product( $post->ID ); $short_description = apply_filters( 'woocommerce_short_description', $post->post_excerpt ); ?> <h1><?php echo esc_attr( $product->get_id() ); ?></h1> <div class="woocommerce-product-details__short-description"> <?php echo $short_description; ?> </div> <form class="cart" action="<?php echo esc_url( get_permalink() ); ?>" method="post" enctype="multipart/form-data"> <div class="iconic-engraving-field"> <label for="iconic-engraving">Engraving (10 characters)</label> <input type="text" id="iconic-engraving" name="iconic-engraving" placeholder="Enter engraving text" maxlength="10"> </div> <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt wp-element-button">Dodaj do koszyka</button> </form> <?php do_action( 'woocommerce_after_main_content' ); get_footer(); ?>
关键修改说明
- 手动通过
wc_get_product( $post->ID )初始化产品对象,确保$product可用 - 表单的
action属性用get_permalink()动态获取当前产品页面链接,替代硬编码URL - 加入购物车按钮的
value属性用$product->get_id()动态获取产品ID,替代固定值14
内容的提问来源于stack exchange,提问作者Tomek
相关产品推荐
相关产品推荐

