I'm trying to find if it's possible to dynamically generate functions and hooks. All functions do the same thing, and all hooks are essentially the same.
Here's an example of a hook/function combo:
add_action( 'woocommerce_single_product_summary', 'cx_inputKVA_show', 5 );
function cx_inputKVA_show() {
global $product;
// Do not show this on variable products
if ( $product->product_type <> 'variable' ) {
$inputKVA = get_post_meta( $product->id, 'cx_inputKVA', true );
if ( $inputKVA <> '' ) {
echo '<div class="woocommerce_msrp">';
_e( 'Input KVA: ', 'woocommerce' );
echo '<span class="woocommerce-cx_inputKVA">' . _e( $inputKVA ) . '</span>';
echo '</div>';
}
}
}
I want to use an array like:
$fieldset = array(
array(
1 => 'slug',
2 => 'title'
)
array(
1 => 'slug',
2 => 'title'
)
);
And then use a foreach()
loop to generate 3 hooks and 3 functions for each nested array.
Before, I was just writing each one separately, but now I need to generate for 23 items and it's too much code, too messy to change.
It would make the hook like:
add_action( 'woocommerce_single_product_summary', 'cx_[plug]_show', 5 );
and the function like
function cx_inputKVA_show() {
global $product;
// Do not show this on variable products
if ( $product->product_type <> 'variable' ) {
$[plug] = get_post_meta( $product->id, 'cx_[plug]', true );
if ( $[plug] <> '' ) {
echo '<div class="woocommerce_msrp">';
_e( '[title]: ', 'woocommerce' );
echo '<span class="woocommerce-cx_[plug]">' . _e( $[plug] ) . '</span>';
echo '</div>';
}
}
}
Answer------------------ Since Milo is a genius, I got this done much simpler by just looping through the array inside of the function, instead of trying to generate a new function dynamically for each item. The array contains 'slug' and 'title' attributes, and here's the function:
function cx_product_field() {
global $fieldset;
foreach ( $fieldset as $field ){
woocommerce_wp_text_input(
array(
'id' => 'cx_'.$field['slug'],
'class' => 'wc_input_text',
'label' => __( $field['title'], 'woocommerce' )
)
);
}
}