I'm developing an eCommerce site with WordPress+WooCommerce.
I added buttons to certain products in the Short Description field in order to quickly select certain number of products to be added in the cart (this is because I have different offers, for example: "Buy 4 for the price of 3").
I have a script like this in the general jquery file:
<script>
function pack4() { document.getElementById("quantity").value = "4"; }
function pack8() { document.getElementById("quantity").value = "8"; }
</script>
And this is an example of the code I have in some products Short Description:
<span><strong>4x3 Pack:</strong>TOTAL<strong>$1800</strong></span>
<button class="select" onclick="pack4()">Select</button>
Everything works and whenever you click on every button the order quantity adds the corresponding number.
The thing is: Whenever my client (who usually edits products) click on the Text/Visual flap of Short Description, the onclick="pack4()"
code disappears. I guess WordPress/WooCommerce have got some jQuery filter that erases this kind of codes. I need it to stop doing that, because the client regularly edits things (and of course they don't know anything about coding). Otherwise, I have to add the code again every time.
I also suspect WP/WC also filters it without needing to click on this Text/Visual flap (but I might be wrong about that).
Anyone knows what to do?
Thanks!
The easiest and accurate way is to create a custom shortcode this way:
if( !function_exists('display_product_button_pack') ) {
function display_product_button_pack( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'pack' => '4', // default pack is 4
),
$atts,
'button_pack'
);
$output = '<button class="select" onclick="pack'.$atts['pack'].'()">Select</button>';
return $output;
}
add_shortcode( 'button_pack', 'display_product_button_pack' );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and works.
USAGE:
There is an optional pack
argument in your shortcode, which default value is 4
…
For your Pack 8 for example, you will insert this in the short description product editor:
[button_pack pack="8"]
This will output this html:
<button class="select" onclick="pack8()">Select</button>
For the Pack 4, as default argument value is already 4 you just use this:
[button_pack]