如何重写SEO by Rank Math插件的WC_Vars类get_product_price()方法?
重写Rank Math的get_product_price()方法
方法1:使用Rank Math内置过滤器(推荐)
Rank Math的WC_Vars::get_product_price()方法内置了过滤器,直接通过它修改价格是最稳妥的方式,无需重写整个类方法。
在主题的functions.php文件里添加以下代码:
add_filter( 'rank_math/woocommerce/product_price', 'custom_rank_math_product_price', 10, 2 ); function custom_rank_math_product_price( $price, $product ) { // 这里编写你的自定义价格逻辑 // 示例:返回产品的会员专属价格 $member_price = get_post_meta( $product->get_id(), '_member_price', true ); if ( $member_price ) { return wc_price( $member_price ); } // 如果没有自定义价格,返回原价格 return $price; }
方法2:重写WC_Vars类(仅当过滤器不可用时)
如果上述过滤器不存在,你可以通过类重写机制替换原类,但要注意版本兼容性:
- 在主题或自定义插件中创建继承类:
class Custom_Rank_Math_WC_Vars extends RankMath\WooCommerce\WC_Vars { /** * 重写产品价格获取方法 */ public function get_product_price( $product ) { // 自定义价格逻辑示例:显示不含税价格 $price = $product->get_price_excluding_tax(); return wc_price( $price ); } }
- 替换原类实例:
add_action( 'plugins_loaded', 'replace_rank_math_wc_vars', 11 ); function replace_rank_math_wc_vars() { if ( class_exists( 'RankMath\WooCommerce\WC_Vars' ) ) { global $rank_math; $rank_math->woocommerce = new Custom_Rank_Math_WC_Vars(); } }
注意事项
- 优先用过滤器,类重写可能在Rank Math版本更新后出现兼容问题。
- 修改后记得清空Rank Math的缓存,确保新逻辑生效。
内容的提问来源于stack exchange,提问作者Vivi
相关产品推荐
相关产品推荐

