Home > other >  WordPress add_filter passing hook name
WordPress add_filter passing hook name

Time:09-14

I'd like to add a filter to Woocommerce product export to add columns but I'd like to add 5 columns using the same hook.

Is it possible to pass the hook name into the filter to allow me to determine which column the data is returned to?

For example, I want to run the following to populate 5 columns using same function (add_export_data) but the returned value would have to be determined by the hook name (containing the col number).

add_filter( 'woocommerce_product_export_product_column_val1', 'add_export_data', 10, 2 );
add_filter( 'woocommerce_product_export_product_column_val2', 'add_export_data', 10, 2 );
add_filter( 'woocommerce_product_export_product_column_val3', 'add_export_data', 10, 2 );
add_filter( 'woocommerce_product_export_product_column_val4', 'add_export_data', 10, 2 );
add_filter( 'woocommerce_product_export_product_column_val5', 'add_export_data', 10, 2 );

So ideally the function would be able to determine the hook name and then choose the relevant data to return as the value.

Thanks

CodePudding user response:

From the 3rd argument, you can get the column ID then you can return the value conditionally.

Here is an example code.

/**
 * Return custom columns data.
 *
 * @param string     $value     Column value.
 * @param WC_Product $product   Product object.
 * @param string     $column_id Column ID.
 *
 * @return string
 */
function add_export_data( $value, $product, $column_id ) {
    switch ( $column_id ) {
        case 'val1':
            // Get the value from meta or any other way you want.
            $value = $product->get_meta( 'product_custom_text', true, 'edit' );
            break;
        case 'val2':
            // Get the value from meta or any other way you want.
            $value = $product->get_meta( 'product_custom_text', true, 'edit' );
            break;
        default:
            break;
    }

    return $value;
}
add_filter( 'woocommerce_product_export_product_column_val1', 'add_export_data', 10, 3 );
add_filter( 'woocommerce_product_export_product_column_val2', 'add_export_data', 10, 3 );
add_filter( 'woocommerce_product_export_product_column_val3', 'add_export_data', 10, 3 );
add_filter( 'woocommerce_product_export_product_column_val4', 'add_export_data', 10, 3 );
add_filter( 'woocommerce_product_export_product_column_val5', 'add_export_data', 10, 3 );
  • Related