Search code examples
phpwordpresswoocommercesettingsproduct

Retrieving options from settings page Wordpress


I am adding a bulk discount functionality to my wordpress site, and I need other members of my team to be able to alter some settings without editing the code directly. I used a settings page generator, but I'm having trouble retrieving the options. Here are the notes from the generator:

/* 
 * Retrieve this value with:
 * $group_discounts_options = get_option( 'group_discounts_option_name' ); // Array of All Options
 * $group_a_minimum_1_0 = $group_discounts_options['group_a_minimum_1_0']; // Group A Minimum 1
 * $group_a_discount_1_1 = $group_discounts_options['group_a_discount_1_1']; // Group A Discount 1
 * $group_a_minimum_2_2 = $group_discounts_options['group_a_minimum_2_2']; // Group A Minimum 2
 * $group_a_discount_2_3 = $group_discounts_options['group_a_discount_2_3']; // Group A Discount 2
 * $group_b_minimum_1_4 = $group_discounts_options['group_b_minimum_1_4']; // Group B Minimum 1
 * $group_b_discount_1_5 = $group_discounts_options['group_b_discount_1_5']; // Group B Discount 1
 * $group_b_minimum_2_6 = $group_discounts_options['group_b_minimum_2_6']; // Group B Minimum 2
 * $group_b_discount_2_7 = $group_discounts_options['group_b_discount_2_7']; // Group B Discount 2
 * $group_c_minimum_1_8 = $group_discounts_options['group_c_minimum_1_8']; // Group C Minimum 1
 * $group_c_discount_1_9 = $group_discounts_options['group_c_discount_1_9']; // Group C Discount 1
 * $group_c_minimum_2_10 = $group_discounts_options['group_c_minimum_2_10']; // Group C Minimum 2
 * $group_c_discount_2_11 = $group_discounts_options['group_c_discount_2_11']; // Group C Discount 2
 */

And here's how I tried to implement the options:

add_filter( 'woocommerce_after_add_to_cart_button', 'group_discount_test', 10, 3 );
function group_discount_test( $post_id, $group_discounts_options ){
    global $product;

    if ( function_exists( 'method_exists' ) && method_exists( $product, 'get_id' ) ) {
        $product_id = $product->get_id();
    } else {
        $product_id = $product->id;
    }
    $post_id = $product_id;
    
    if ( get_post_meta( $product_id, '_alg_wc_pq_min', true ) > 19 ){
        echo $group_a_minimum_1_0;
    }
}

This causes all front end product pages to hang. What am I doing wrong?


Solution

  • Try the following simplified and complete code version instead:

    add_filter( 'woocommerce_after_add_to_cart_button', 'group_discount_test');
    function group_discount_test(){
        global $product;
    
        $option = get_option('group_discounts_option_name'); // Get option data
        
        if ( $product->get_meta('_alg_wc_pq_min') > 19 && isset($option['group_a_minimum_1_0']) ){
            echo $option['group_a_minimum_1_0'];
        }
    }
    

    It should work