I'm creating a plugin which will add "-" and "+" increment buttons around quantity input field. I left some essential lines to more clearly present the problem.
I created class qty_increment_buttons_settings
with 2 settings in admin, numeric value and checkbox, using settings API. This numeric value is passed as a variable to js file. I wrote similar plugin before and it worked, but here it's more complex - I would like to use this new instance of class in my other functions, for example within qib_create_button
to access checkbox value, through public function qib_get_settings
defined within this class.
Also, is there any way I could specify true
and false
within add_action
hooks, so I don't need to create 2 extra functions?
add_action( 'template_redirect', 'run_qib' );
function run_qib() {
if (! is_cart() && ! is_product()) return; // Only if it's product or cart page.
add_action( 'wp_enqueue_scripts', 'qty_increment_buttons' );
}
function qty_increment_buttons( ) {
$plugin_slug = 'qty-increment-buttons-for-woocommerce';
$plugin_short_slug = 'qty-increment-buttons';
add_action('wp_head', 'qib_apply_styles', 20);
wp_enqueue_script( $plugin_short_slug, plugins_url() . '/' . $plugin_slug . '/js/' . $plugin_slug . '.js', array('jquery'), '', true);
$qib_settings_page = new qty_increment_buttons_settings();
add_action( 'woocommerce_before_add_to_cart_quantity', 'qib_create_button_before' );
add_action( 'woocommerce_after_add_to_cart_quantity', 'qib_create_button_after' );
// js variable name => variable value
$data = array (
'qib_button_size' => $qib_settings_page->qib_get_settings('qib_button_size'),
);
wp_localize_script( $plugin_short_slug, 'phpVars', $data );
}
function qib_create_button_before() {
echo qib_create_button( true );
}
function qib_create_button_after() {
echo qib_create_button( false );
}
function qib_create_button( $is_before ) {
$sign = ( 1 == $qib_settings_page->qib_get_settings('qib_minus_first') && $is_before === true ? '-' : '+' );
return sprintf('<button type="button" class="%1$s" >%2$s</button>', $sign === '-' ? 'minus' : 'plus', $sign );
}