问题描述
我对WordPress和WooCommerce还是陌生的,因此对解释不力表示歉意.
I'm totally new to WordPress and WooCommerce, so apologies for the poor explanation.
我有此代码:
$text = apply_filters( 'prefix_xml_feeds_productname_variant', $text, $product_item->ID, $vars->ID );
并且需要在我的函数中显示$vars->ID
:
所以我得到了
function custom_product_name() {
global $product;
$product_name = $product->get_name();
$sku = $product->get_sku();
$text = 'Example.com ' . $sku . ' ' . $product_name . ' ' . $vars->ID;
return $text;
}
add_filter( 'prefix_xml_feeds_productname_variant', 'custom_product_name' );
如何在回调函数中访问$vars
变量值?
How can I access $vars
variable value in my callback function?
推荐答案
如您所见,apply_filters( 'prefix_xml_feeds_productname_variant', $text, $product_item->ID, $vars->ID );
包含3个参数
As you can see apply_filters( 'prefix_xml_feeds_productname_variant', $text, $product_item->ID, $vars->ID );
contains 3 parameters
所以您可以像使用它
function custom_product_name( $text, $product_id, $vars_id ) {
// Get product object
$product = wc_get_product( $product_id );
// Is a product
if ( is_a( $product, 'WC_Product' ) ) {
// Get product name
$product_name = $product->get_name();
// Get product sku
$sku = $product->get_sku();
// Output
$text = 'Example.com ' . $sku . ' ' . $product_name . ' ' . $vars_id;
}
return $text;
}
add_filter( 'prefix_xml_feeds_productname_variant', 'custom_product_name', 10, 3 );
更多信息: https://docs.woocommerce .com/document/introduction-to-hooks-actions-and-filters/
使用滤清器钩子
在使用apply_filter( 'filter_name', $variable );
的代码中始终调用过滤器挂钩.要操作传递的变量,您可以执行以下操作:
Filter hooks are called throughout are code using apply_filter( 'filter_name', $variable );
. To manipulate the passed variable, you can do something like the following:
add_filter( 'filter_name', 'your_function_name' );
function your_function_name( $variable ) {
// Your code
return $variable;
}
使用过滤器,您必须返回一个值.
With filters, you must return a value.
这篇关于从WooCommerce中的apply_filters('prefix_xml_feeds_productname_variant')函数获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!