woocommerce 更改价格位置 [已关闭]

问题描述 投票:0回答:2

当我尝试在页面上的主要内容之前呈现产品价格时,出现此错误。

Fatal error: Uncaught Error: Call to a member function get_price_html() on string in /wp-content/plugins/woocommerce/templates/single-product/price.php:27 

这是我的代码:

 //the remove action works fine

remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);

//this breaks it

add_action('woocommerce_before_main_content', 'woocommerce_template_single_price', 40);

我认为因为我试图在主要内容之前获取价格,所以我需要确保加载全局

$product

如何确保全局

$product
已加载?

php wordpress woocommerce product
2个回答
1
投票

我认为你不想做的事情是不可能的。您正在将price.php 的渲染移至循环之前和添加到购物车表单之外。然后

get_price_html()
需要变量
$price
,这里没有。

为此,我想您需要在

price.php
模板中进行如下更改:

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

global $product;
$price = esc_attr( $product->get_price() );
// $price = woocommerce_price( $product->regular_price ); // or this one
// $price = woocommerce_price( $product->sale_price ); // or this one too
?>

<div itemprop="offers" itemscope itemtype="http://schema.org/Offer">

<p class="price"><?php echo $product->get_price_html(); ?></p>

<meta itemprop="price" content="<?php echo esc_attr( $product->get_price() ); ?>" />
    <meta itemprop="priceCurrency" content="<?php echo esc_attr( get_woocommerce_currency() ); ?>" />
    <link itemprop="availability" href="http://schema.org/<?php echo $product->is_in_stock() ? 'InStock' : 'OutOfStock'; ?>" />

</div>

或将

$product->get_price_html()
替换为
esc_attr( $product->get_price() );
您可能还需要在其中插入循环......

参考:通过主题覆盖模板


0
投票

只需复制单个产品价格模板中的代码并将其粘贴到您的挂钩函数中即可。 https://github.com/woothemes/woocommerce/blob/master/templates/single-product/price.php

remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);

function price_in_title_row() {

if ( ! defined( 'ABSPATH' ) ) {
      exit; // Exit if accessed directly
}
global $product;
?>

<div class="price_in_title_row" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
    <h3><?php echo $product->get_price_html(); ?></h3>
    <meta itemprop="price" content="<?php echo esc_attr( $product->get_display_price() ); ?>" />
    <meta itemprop="priceCurrency" content="<?php echo esc_attr( get_woocommerce_currency() ); ?>" />
    <link itemprop="availability" href="http://schema.org/<?php echo $product->is_in_stock() ? 'InStock' : 'OutOfStock'; ?>" />
</div>

}

add_action('woocommerce_before_single_product', 'price_in_title_row', 50);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.