I’m totally new to WordPress and WooCommerce, so apologies for the poor explanation.
I have this code:
$text = apply_filters( 'prefix_xml_feeds_productname_variant', $text, $product_item->ID, $vars->ID );
And need to display $vars->ID
in my function:
So I got:
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' );
How can I access $vars
variable value in my callback function?
Advertisement
Answer
As you can see apply_filters( 'prefix_xml_feeds_productname_variant', $text, $product_item->ID, $vars->ID );
contains 3 parameters
So you could use it like
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 );
More information: https://docs.woocommerce.com/document/introduction-to-hooks-actions-and-filters/
Using filter hooks
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.