Woocommerce product variation selection with buttons instead dropdown menu? - wordpress

I am new to wordpress.
I am creating a ecommerge website with wordpress 4.5(latest) + woocommerge 2.5.5(latest) + storefront theme.
I have a product with 2 variations with different prices.
When I select a variation from dropdown menu displaying variation price under dropdown.
Product detail page with 2 variations shown as below:
I want to select variantions with buttons instead dropdown, and update product price on product page instead show below of dropdown.
If I create different products for each variantion and add custom html for buttons and link each variation products with each other, this works but this is very painful.
How to make variations selection with buttons instead dropdown shown as below picture

I was made variantion selection with buttons instead select box with javascript plugin.
I created a plugin and included a js file to product page that creates buttons for each variant at product page and hide select box.
Pros:
Not changed any file of wordpress core, woocommerce and storefront theme.
myplugin.php
define('MYPLUGIN__VERSION', '1.0');
function variant_selection_with_buttons() {
if (is_product()) {
#TODO serve .min.js on production
$js_file = plugins_url('/js/variant-selection-with-buttons.js', __FILE__);
wp_register_script(
'variant_selection_with_buttons_js',
$js_file,
array('jquery'),
MYPLUGIN__VERSION,
true
);
wp_enqueue_script('variant_selection_with_buttons_js');
}
}
add_action( 'wp_enqueue_scripts', 'variant_selection_with_buttons');
js/variations-selection-with-buttons.js
;(function($, window, document, undefined){
var variations = $('.variations_form').data('product_variations'),
requiredVals = {},
selectedVariation;
$('.woocommerce-variation').remove();
$('table.variations').hide();
$(variations).each(function(i, item){
var variationSlug;
$.each(item['attributes'], function(key, value){
variationSlug = value;
return;
});
requiredVals[variationSlug] = {
'price_html': item['price_html'],
'variation_description': item['variation_description'],
};
});
var $variationChangerCon = $('<div/>', {
'id': 'variationChangerCon',
'style': 'margin-bottom:5px',
});
$variationChangerCon.append('<div class="variationBtns"/>');
$('table.variations').find('select option').each(function(index){
var $option = $(this);
if (!$option.val()) return;
if ($option.is(':selected')){
selectedVariation =$option.val();
}
var $button = $('<a/>', {
'class': 'variation-btn single_add_to_cart_button button btn-info PvariationLink',
'text': $option.text(),
'style': 'margin-right:2px;',
});
$button.attr('data-slug', $option.val());
$variationChangerCon.find('.variationBtns').append($button);
});
$variationChangerCon.append('<div class="variationDesc"/>');
$variationChangerCon.insertBefore('.entry-summary div[itemprop="description"]');
$('div.product').on('click', '.variation-btn', function(){
var $this = $(this),
item = requiredVals[$this.data('slug')];
itemDesc = requiredVals[$this.data('slug')];
$('.variation-btn').removeClass('disabled');
$this.addClass('disabled');
$('table.variations select').val($this.data('slug')).trigger('change')
$('.entry-summary div[itemprop="offers"] p.price')
.html(item['price_html'])
$variationChangerCon.find('.variationDesc').html(item['variation_description']);
});
if (selectedVariation) {
$('.variationBtns .variation-btn[data-slug="'+ selectedVariation +'"]').trigger('click');
} else {
/*
If default variation not selected in admin pane
`selectedVariation` become undefined . So select first variation/
*/
$('.variationBtns .variation-btn:eq(0)').trigger('click');
}
})( jQuery, window, document, undefined );

Related

Suggestions on how to extend WordPress shortcode Edit button without losing its functionality

I'd like to extend the WordPress shortcode Edit button and have my own functionality onClick and at the same time don't lose/overwrite the one the WordPress has.
Here is the code I have right now (which works) but this overwrites the WordPress onClick which doesn't work any more and obviously I don't want to have that.
editor.addButton( 'wp_view_edit', {
tooltip : 'Edit',
icon : 'dashicon dashicons-edit',
onclick : function() {
// here goes my code for custom functionality
}
} );
And here is the original code from WP found in /wp-incldes/js/tinymcs/plugins/wp-view/plugins.js
editor.addButton( 'wp_view_edit', {
tooltip: 'Edit|button', // '|button' is not displayed, only used for context
icon: 'dashicon dashicons-edit',
onclick: function() {
var node = editor.selection.getNode();
if ( isView( node ) ) {
wp.mce.views.edit( editor, node );
}
}
} );

How to display Total cost of products added in wishlist using yith woocommerce wishlist plugin?

I'm developing E-Commerce website using Wordpress and Woocommerce plugins.
I've installed yith Woocommerce wishlist plugin for user to add product in wishlist, it's display unit product cost, add to cart button and product image.
I want to display Total product cost added in wishlist and for that add to cart button also. Please help.
To display Total product cost with YITH Woocommerce Wishlist plugin, you can do this with Jquery :
var myArray = $(".wishlist_table .amount"); // Recover all product cost
var result = 0;
for (var i = 0; i<myArray.length; i++) {
result += parseFloat(myArray[i].childNodes["0"].data); // Make the sum
}
$("#som").text(result); // Place total in a HTML element - my ID is "som" but no matter what it is
$(".remove_from_wishlist").live('click', function(){ // When user remove item with AJAX
var href = $(this).attr('href'); // Find parent
href = href.replace(/\D/g,'');
var arrayTo = $('#yith-wcwl-row-'+href+' .amount').text();
arrayTo = parseFloat(arrayTo.replace(/\u20ac/g, '')); // u20ac is unicode character for euro sign but works with just 'D' instead
var recoverTotal = $("#som").text(); // Recover the total
var result2 = recoverTotal - arrayTo;
$("#som").text(result2); // Display the final result
});
You have to put this code in a shortcode function. It works for me.
I am not sure which wishlist plugin you're using as there are a few wishlist plugins.
However, I have written a solution for this while using YITH Woocommerce Wishlist plugin. Sharing that code here if that helps.
function tnc_wishlist_summary_cart(){
global $woocommerce;
$wl_items = YITH_WCWL()->get_products();
$product_price = 0;
foreach ($wl_items as $key => $item) {
$the_product = wc_get_product($item['prod_id']);
$product_price += $the_product->get_price();
if(isset($_REQUEST['add_all_to_cart'])){
$woocommerce->cart->add_to_cart($item['prod_id']);
}
}
$output = 'Total Price: '.$product_price;
$output .= "<a href='?add_all_to_cart'>Add All to Cart</a>";
return $output;
}
add_shortcode( 'tnc-wishlist-summary', 'tnc_wishlist_summary_cart' );
Put This code in functions.php or inside a standalone plugin and put the following shortcode on the Wishlist page.
[tnc-wishlist-summary]
It will output Total Price and a link for adding all to cart. Not styled though. You need to style it according to your needs.
Thanks

WooCommerce Product Gallery: Swap Featured Image with Selected Thumbnail

Woocommerce displays the product gallery on a lightbox or new tab by default. I would like to display the product gallery on the box where the product image is displayed. I tried WooCommerce Dynamic Gallery but the LITE version doesn't allow me to display all the product gallery images on each product. Also, it displays the image on the product description.
Can anyone suggest me a wordpress plugin or coding that can display the product gallery dynamically ? Thanks a lot.
It's possible with some straightforward jquery (see below). You'll also need to override the default lightbox that WooCommerce includes for the gallery.
I believe that it's possible to disable it from the admin under WC -> Settings -> Products -> Display. But you can also remove the styles and scripts directly.
I haven't tested this code on a fresh install of WooCommerce--this is some modified code from a site with a heavily customized product gallery that includes video support.
You'll need to include this in your theme's functons.php file, etc. etc.
add_action( 'wp_enqueue_scripts', 'wc_remove_lightboxes', 99 );
/**
* Remove WooCommerce default prettyphoto lightbox
*/
function wc_remove_lightboxes() {
// Styles
wp_dequeue_style( 'woocommerce_prettyPhoto_css' );
// Scripts
wp_dequeue_script( 'prettyPhoto' );
wp_dequeue_script( 'prettyPhoto-init' );
wp_dequeue_script( 'fancybox' );
wp_dequeue_script( 'enable-lightbox' );
}
/* Customize Product Gallery */
/**
* Click on thumbnail to view image for single product page gallery. Includes
* responsive image support using 'srcset' attribute introduced in WP 4.4
* #link https://make.wordpress.org/core/2015/11/10/responsive-images-in-wordpress-4-4/
*/
add_action( 'wp_footer', 'wc_gallery_override' );
function wc_gallery_override()
{
// Only include if we're on a single product page.
if (is_product()) {
?>
<script type="text/javascript">
( function( $ ) {
// Override default behavior
$('.woocommerce-main-image').on('click', function( event ) {
event.preventDefault();
});
// Find the individual thumbnail images
var thumblink = $( '.thumbnails .zoom' );
// Add our active class to the first thumb which will already be displayed
//on page load.
thumblink.first().addClass('active');
thumblink.on( 'click', function( event ) {
// Override default behavior on click.
event.preventDefault();
// We'll generate all our attributes for the new main
// image from the thumbnail.
var thumb = $(this).find('img');
// The new main image url is formed from the thumbnail src by removing
// the dimensions appended to the file name.
var photo_fullsize = thumb.attr('src').replace('-300x300','');
// srcset attributes are associated with thumbnail img. We'll need to also change them.
var photo_srcset = thumb.attr('srcset');
// Retrieve alt attribute for use in main image.
var alt = thumb.attr('alt');
// If the selected thumb already has the .active class do nothing.
if ($(this).hasClass('active')) {
return false;
} else {
// Remove .active class from previously selected thumb.
thumblink.removeClass('active');
// Add .active class to new thumb.
$(this).addClass('active');
// Fadeout main image and replace various attributes with those defined above. Once the image is loaded we'll make it visible.
$('.woocommerce-main-image img').css( 'opacity', '0' ).attr('src', photo_fullsize).attr('srcset', photo_srcset).attr('alt', alt).load(function() {
$(this).animate({ opacity: 1 });
});
return false;
}
});
} )( jQuery );
</script>
<?php
}
}

In wordpress to mark required fields in Add New Post page

in WP 4.2 opening Add New Post page and without editing any fields, clicking on "Publish" button page is submitted and reopened, but no any of fields are marked with red background color as required.
How to make it? Seems, that is original behauvior of this page.
I want it to work like editor of categories, when in similar situation field name is marked with red background color as required.
Also I added several fields to New Post page using register_post_type function and I aslo want to marked with red background color as required. Which is the best way for this?
Thanks!
You can call your jquery validation by your self using below code,
Add this code in theme's functions.php and custom.js in your theme js folder
add_action( 'admin_print_scripts-post-new.php', 'custom_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'custom_admin_script', 11 );
function custom_admin_script() {
global $post_type;
// Post type = "post" or "page" you can load script wheater it is post or page , if page then change 'post' to 'page' in below condition
if( 'post' == $post_type )
wp_enqueue_script( 'custom-admin-script', get_stylesheet_directory_uri() . '/js/custom.js' );
}
custom.js
jQuery(document).ready(function ($) {
if ($("#post").length > 0) {
var frm = true;
$("#publish").click(function () {
var title = $("#title").val();
var excerpt = $("#excerpt").val();
// your custom field variable goes here
if (jQuery.trim(title) == "" || jQuery.trim(excerpt) == "") {
frm = false;
}
if (frm == false) {
$("#publish").prop('disabled', true);
} else {
$("#publish").prop('disabled', false);
}
});
}
});

Show Metabox In Write Post/Page When Template is Changed

I can create the metaboxes just fine and if I assign a metabox to a specific template(s), they appear just fine in the Add New Page screen, but only after the new page has been saved.
Is there a way to show/hide the metabox when the template value has changed...without having to save the page first?
Add to WP admin page
jQuery(document).ready(function($) {
$("#page_template").live('change',function(){
var getCurrentTemplate = $("#page_template").val();
if( getCurrentTemplate == "template-contact.php"){
$("#pageheading-hide").attr('checked', true);
$("#pageheading").css({'display':'block'});
}
else{
$("#pageheading-hide").attr('checked', false);
$("#pageheading").css({'display':'none'});
}
});
});

Resources