Woocommerce Shopping Cart Icon - php

I have a woocommerce cart icon in my main navigation. I want that icon to show a if the cart has items in it. If not that would be removed. I have tried the code below and it does not do what I intended it to. Ideas?
if($items_txt = $count_value === 1 ){
$html .= '<span class="xoo-wsc-sc-count">1</span>';}
elseif($items_txt = $count_value === 0 ){
$html .= '';}
Here is the full original code snippet.
<?php
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
$sy_options = get_option('xoo-wsc-sy-options');//Style options
$options = get_option('xoo-wsc-gl-options');
$count_type = isset( $options['bk-count-type']) ? $options['bk-count-type'] : 'qty_count'; //Count Type
$cart_items_total = wc_price(WC()->cart->subtotal);
$bk_cubi = isset( $sy_options['bk-cubi']) ? $sy_options['bk-cubi'] : ''; // Custom basket icon
if( !$bk_cubi ){
$bk_bit = isset( $sy_options['bk-bit']) ? $sy_options['bk-bit'] : 'xoo-wsc-icon-basket1'; // Basket Icon Type
}
$html = '<a class="xoo-wsc-sc-cont">';
if( $bk_cubi ){
$html .= '<img src="'.$bk_cubi.'" class="xoo-wsc-sc-icon">';
}
else{
$html .= '<span class="xoo-wsc-sc-icon '.$bk_bit.'"></span>';
}
if($count_type == 'qty_count'){
$count_value = WC()->cart->get_cart_contents_count();
}
elseif($count_type == 'item_count'){
$count_value = count(WC()->cart->get_cart());
}
$items_txt = $count_value === 1 ? __('item','side-cart-woocommerce') : __('items','side-cart-woocommerce');
$html .= '<span class="xoo-wsc-sc-count">'.'</span>';
//$html .= '<span class="xoo-wsc-sc-count">'.$count_value.'</span>';
//$html .= '<span class="xoo-wsc-sc-total">'.$cart_items_total.'</span>';
$html .= '</a>';
echo $html;

I think if you change this if:
if( $bk_cubi ){
$html .= '<img src="'.$bk_cubi.'" class="xoo-wsc-sc-icon">';
}
else{
$html .= '<span class="xoo-wsc-sc-icon '.$bk_bit.'"></span>';
}
To:
if ($bk_cubi)
{
$html .= '<img src="'.$bk_cubi.'" class="xoo-wsc-sc-icon">';
}
else
{
if($count_value == 1 )
{
$html .= '<span class="xoo-wsc-sc-count">1</span>';
}
}
You'll get what you want.
Also, a single = is assignment operator. == is for checking whether values are equal to one another.

You can use the woocommerce_add_to_cart_fragments hook to check real-time woocommerce cart items.
add_filter( 'woocommerce_add_to_cart_fragments', 'woo_cart_icon_count' );
function woo_cart_icon_count( $fragments ) {
$cart_count = WC()->cart->cart_contents_count;
if($cart_count > 0) {
// your code here
}
}
For more detail, you can check the tutorial here.

Related

Placing the Search icon under the Mobile menu

Unfortunately, I am doing something wrong. I have a function. In this function the hamburger menu is displayed. I still want to show the search icon under the menu. But as soon as I add the a tag and no span the search icon is shown somewhere under the menu see photo. But if I change the a tag to a span then the search button does not work anymore. What am I doing wrong. Can someone help me.
if ( ! function_exists( 'tonda_select_get_mobile_navigation_icon_html' ) ) {
/**
* Loads mobile navigation icon HTML
*/
function tonda_select_get_mobile_navigation_icon_html() {
$mobile_icon_icon_source = tonda_select_options()->getOptionValue( 'mobile_icon_icon_source' );
$mobile_icon_icon_pack = tonda_select_options()->getOptionValue( 'mobile_icon_icon_pack' );
$mobile_icon_svg_path = tonda_select_options()->getOptionValue( 'mobile_icon_svg_path' );
$mobile_navigation_icon_html = '';
if ( ( $mobile_icon_icon_source == 'icon_pack' ) && ( isset( $mobile_icon_icon_pack ) ) ) {
$mobile_navigation_icon_html .= tonda_select_icon_collections()->getMobileMenuIcon($mobile_icon_icon_pack);
} else if ( $mobile_icon_icon_source == 'predefined' ) {
$mobile_navigation_icon_html .= '<span class="qodef-mm-icons-columns">';
$mobile_navigation_icon_html .= '<span class="qodef-mm-icons col1">';
$mobile_navigation_icon_html .= '<span class="qodef-mm-line qodef-mm-line-1"></span>';
$mobile_navigation_icon_html .= '<span class="qodef-mm-line qodef-mm-line-2"></span>';
$mobile_navigation_icon_html .= '<span class="qodef-mm-line qodef-mm-line-3"></span>';
$mobile_navigation_icon_html .= '</span>';
$mobile_navigation_icon_html .= '<span class="qodef-mm-icons col2">';
$mobile_navigation_icon_html .= '<a class="qodef-search-opener qodef-icon-has-hover qodef-search-opener-icon-pack" href="javascript:void(0)">
<span class="qodef-search-opener-wrapper">
<span aria-hidden="true" class="qodef-icon-font-elegant icon_search "></span> </span>
</a>';
$mobile_navigation_icon_html .= '</span>';
$mobile_navigation_icon_html .= '</span>';
} else if ( isset( $mobile_icon_svg_path ) ) {
$mobile_navigation_icon_html .= $mobile_icon_svg_path;
}
return $mobile_navigation_icon_html;
}
}

Display and render specific custom product attributes to images on single product pages in Woocommerce

I am working on a solution to have specific product attributes on a single product page. Based on Display specific custom product attributes on single product pages in Woocommerce answer code, I made some little changes here below
to display the selected attribute on single product pages:
add_action( 'woocommerce_single_product_summary', 'display_some_product_attributes', 25 );
function display_some_product_attributes(){
// HERE define the desired product attributes to be displayed
$defined_attributes = array('attributeB', 'attributeC', 'attributeD');
global $product;
$attributes = $product->get_attributes();
echo '<div style="font-size: 20px; font-weight: 500; margin-bottom: 5px; text-transform: uppercase;"><span>Sensorik</span></div>';
if ( ! $attributes ) {
return;
}
$out = '<ul class="taste-attributes">';
foreach ( $attributes as $attribute ) {
// Get the product attribute slug from the taxonomy
$attribute_slug = str_replace( 'pa_', '', $attribute->get_name() );
// skip all non desired product attributes
if ( ! in_array($attribute_slug, $defined_attributes) ) {
continue;
}
// skip variations
if ( $attribute->get_variation() ) {
continue;
}
$name = $attribute->get_name();
if ( $attribute->is_taxonomy() ) {
$terms = wp_get_post_terms( $product->get_id(), $name, 'all' );
// get the taxonomy
$tax = $terms[0]->taxonomy;
// get the tax object
$tax_object = get_taxonomy($tax);
// get tax label
if ( isset ( $tax_object->labels->singular_name ) ) {
$tax_label = $tax_object->labels->singular_name;
} elseif ( isset( $tax_object->label ) ) {
$tax_label = $tax_object->label;
// Trim label prefix since WC 3.0
if ( 0 === strpos( $tax_label, 'Product ' ) ) {
$tax_label = substr( $tax_label, 8 );
}
}
$out .= '<p class="' . esc_attr( $name ) . '">';
$out .= '<span class="attribute-label">' . esc_html( $tax_label ) . ': </span>';
$tax_terms = array();
foreach ( $terms as $term ) {
$single_term = esc_html( $term->name );
// Insert extra code here if you want to show terms as links.
array_push( $tax_terms, $single_term );
}
$out .= '<span class="attribute-value">' . implode(', ', $tax_terms) . '</span></p>';
} else {
$value_string = implode( ', ', $attribute->get_options() );
$out .= '<span class="' . sanitize_title($name) . ' ' . sanitize_title( $value_string ) . '">';
$out .= '<p class="attribute-label">' . $name . ': </p></span>';
}
}
$out .= '</ul>';
echo $out;
}
Then to transform text to an image for some attributes, I use the code below:
``` /**
* Insert JavaScript to replace WooCommerce product attributes text with images.
*/
function my_woocommerce_attributes_images(){
?>
<script>(function() {
var list, index, element, attValue, imgURL;
list = document.getElementsByClassName("attributeA");
for (index = 0; index < list.length; ++index) {
element = list[index];
attValue = element.getElementsByClassName("attribute-value")[0].innerText;
switch (attValue.trim()) {
case "valueA":
imgURL = "/wp-content/uploads/2020/10/cigar.png";
break;
case "valueB":
imgURL = "/wp-content/uploads/2020/10/fish.png";
break;
}
element.innerHTML = '<span class="attribute-label">Atteibute A: </span><img src="' + imgURL + '" width="20" height="20" />';
}
})();</script>
<?php
}
add_action('wp_footer', 'my_woocommerce_attributes_images'); ```
But I have the following problems:
Currently, only one case can be possible. If two ore more are true, it will not load any images. So we need a for each loop here and out put all true values => images. But all of my tryout was not sucessfull.
Currently we have to insert the code multiple times when we want to transform text to images from more than one attribute. I already tried to add a for each loop for list = document.getElementsByClassName("attributeA"); in order taht we can have there something like list = document.getElementsByClassName("attributeA", "attributeB", "attributeB"); But I'm not able to get this to work.
In order to make this more generic, also the element.innerHTML = '<span class="attribute-label">Attribute A: </span><img src="' + imgURL + '" width="20" height="20" />'; should be display the generic current Attribute lable name. But yeah, here I not able to add this in a ore generic way.
Any suggestions are welcome to make it work.

Get label name from product WooCommerce shipping class Id

I want to display product shipping class label(character) instead its id(number). I mean, as seen in the image below, I wnat to chage 0 to Free or flat-rage etc. How or where do I have to edit under the relevant code below? Can I be helped by anybody professional?
enter image description here
The relevant code is
if ($sale_carousel_items_content) {
$carousel_items .= '<ul class="products" style="background:yellow; border:none; padding-left:50px;">';
enter code here
foreach ($sale_carousel_items_content as $item) {
if ( isset( $item['product_id'] ) ) {
$product = new WC_Product( $item['product_id'] );
if ( $product->is_on_sale() ) {
$countdown_container_id = uniqid('countdown',false);
$target = explode("-", $item['target_date']);
$carousel_items .= '<li class="row"><div class="img-wrapper col-xs-12 col-md-6">';
$carousel_items .= ''.$product->get_image( 'shop_catalog' ).'';
$carousel_items .= '<h6>'.$product->get_shipping_class_id().'</h6></div>';
$carousel_items .= '<div class="counter-wrapper col-xs-12 col-md-6"><h6>'.$product->get_name().'</h6>';
// Short Description
$carousel_items .= '<div class="woocommerce-product-details__short-description"><h6>'.$product->get_short_description().'</h6>';
// Sale value in percents
$percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );
$carousel_items .= '<span class="sale-value" style="background:orange;"><font style="font-size:15px;">특판가 </font>-'.$percentage.'% </span>';
$carousel_items .= '<div><h5></h5>';
$carousel_items .= '<div class="price-wrapper"><h5>남은수량: '.$product->get_stock_quantity().'개</h5>';
//$carousel_items .= '<div class="countdown-wrapper">';
if ( $item['pre_countdown_text'] && $item['pre_countdown_text'] != '' ) {
$carousel_items .= '<p>'.esc_attr($item['pre_countdown_text']).'</p>';
}
//$carousel_items .= '<div id="'.$countdown_container_id.'"></div></div>';
//$carousel_items .= '<div class="price-wrapper">'.do_shortcode('[add_to_cart id="'.$item['product_id'].'"]').'</div>';
if ( $target && $target!='' ) {
$carousel_items .='
<script type="text/javascript">
(function($) {
$(document).ready(function() {
var container = $("#'.$countdown_container_id.'");
var newDate = new Date('.$target[0].', '.$target[1].'-1, '.$target[2].');
container.countdown({
until: newDate,
});
});
})(jQuery);
</script>';
}
$carousel_items .= '</div></li>';
}
}
}
$carousel_items .= '</ul>';
}
Final update
Use the following to get the term name (label name) from a product shipping class Id:
$term_id = (int) $product->get_shipping_class_id(); // Get the shipping class Id
$term_name = ''; // Initializing
if( $term_id > 0 ) {
$term = get_term( $term_id, 'product_shipping_class' );
if( is_a( $term, 'WP_Term') ) {
$term_name = $term->name;
}
}
// testing output
echo '<h6>'. $term_name .'</h6>';
So in your code replace the line
$carousel_items .= '<h6>'.$product->get_shipping_class_id().'</h6></div>';
by the following code block:
$shipping_class_id = (int) $product->get_shipping_class_id(); // Get shipping class Id
$shipping_class_name = ''; // Initializing
if ( $shipping_class_id > 0 ) {
$shipping_class_term = get_term( $shipping_class_id, 'product_shipping_class' ); // Get the WP_Term Object
if ( is_a( $shipping_class_term, 'WP_Term') ) {
$shipping_class_name = $shipping_class_term->name; // The label name (term name)
}
}
$carousel_items .= '<h6>'.$shipping_class_name.'</h6></div>'; // Add to output
Tested and works.

WooCommerce Extra Product Options

Any one please help me find the solution to the following:
I want to show specific product option value on woocommerce email template.
The code to show all option value:
public function tm_woocommerce_email_after_row($item_id, $item, $order , $flat=false){
$html = '';
$has_epo = isset($item['item_meta']) && isset($item['item_meta']['_tmcartepo_data']) && isset($item['item_meta']['_tmcartepo_data'][0]);
if ($has_epo){
$epos = maybe_unserialize($item['item_meta']['_tmcartepo_data'][0]);
$current_product_id=$item['product_id'];
$original_product_id = floatval(TM_EPO_WPML()->get_original_id( $current_product_id,'product' ));
if (TM_EPO_WPML()->get_lang()==TM_EPO_WPML()->get_default_lang() && $original_product_id!=$current_product_id){
$current_product_id = $original_product_id;
}
$wpml_translation_by_id=$this->get_wpml_translation_by_id( $current_product_id );
foreach ($epos as $key => $epo) {
if ($epo){
if(!isset($epo['quantity'])){
$epo['quantity'] = 1;
}
if(isset($wpml_translation_by_id[$epo['section']])){
$epo['name'] = $wpml_translation_by_id[$epo['section']];
}
if(!empty($epo['multiple']) && !empty($epo['key'])){
$pos = strrpos($epo['key'], '_');
if($pos!==false) {
$av=array_values( $wpml_translation_by_id["options_".$epo['section']] );
if (isset($av[substr($epo['key'], $pos+1)])){
$epo['value'] = $av[substr($epo['key'], $pos+1)];
}
}
}
if ($flat){
$html .= "\n" . $epo['name'] . ' : ' . $epo['value'];
$html .= "\n" . sprintf( __( 'Quantity: %s', 'woocommerce' ), ( $epo['quantity'] * (float) $item['item_meta']['_qty'][0] ) );
if (!empty($item['item_meta']['tm_has_dpd'])){
}else{
$html .= "\n" . sprintf( __( 'Cost: %s', 'woocommerce' ), (wc_price( (float) $epo['quantity'] * (float) $epo['price'] * (float) $item['item_meta']['_qty'][0] )) );
}
}else{
$html .= '';
$html .= ''.$epo['name'].': '.$epo['value'].'<br/>';
$html .= '';
}
}
}
}
echo $html;
}
I am using this plugin for extra option :
WooCommerce Extra Product Options
Any hint will be much appreciated.
Thank you so much!

Sort Wordpress foreach results by custom field

I've been stuck on this issue all day, and I just keep getting nowhere with it, hoping someone can help!
I'm building a site for a restaurant that has multiple locations and need to list out each drink that exists at each specific location. These drinks need to then be sorted by category (brown, white, tomato, beer, wine). I feel like I'm extremely close to a solution, but I've been banging my head for the last while.
Here's my code:
$drinks = get_posts('post_type=drinks&numberposts=-1');
$show_brown_title = false;
$show_white_title = false;
$show_tomato_title = false;
$show_wine_title = false;
$show_beer_title = false;
if ( $drinks ) {
foreach( $drinks as $drink ) {
$id = $drink->ID;
$drink_location = $drink->drink_location;
if($drink->drink_category == 'Brown' && $drink_location && in_array($site_slug, $drink_location)) {
if($show_brown_title == false) {
echo '<h4><span>Brown</span> Cocktails</h4>';
echo '<ul>';
$show_brown_title = true;
}
echo '<li>';
echo '<span class="drink_title">'.$drink->post_title.'</span>';
echo '<span class="drink_ingredients">'.$drink->drink_ingredients.'</span>';
echo '<span class="drink_price">'.$drink->price_oz.'</span>';
echo '</li>';
}
if($drink->drink_category == 'White' && $drink_location && in_array($site_slug, $drink_location)) {
if($show_white_title == false) {
echo '<h4><span>White</span> Cocktails</h4>';
echo '<ul>';
$show_white_title = true;
}
echo '<li>';
echo '<span class="drink_title">'.$drink->post_title.'</span>';
echo '<span class="drink_ingredients">'.$drink->drink_ingredients.'</span>';
echo '<span class="drink_price">'.$drink->price_oz.'</span>';
echo '</li>';
}
}
}
For the most part, this works. However, I'm running into 2 issues.
I can't figure out how to close the unordered list after I'm done with each category.
This groups by category for the most part, however, if I have a drink that comes later, it will not actually put it into the right category, it'll just go into whatever category is at the bottom. I'm not sure if this is because I'm not closing the unordered list, or if because of the order that the posts are being pulled from WP.
Let me know if I'm explaining this alright, and I really appreciate any help you guys can offer!
Z
Instead of get_posts, you should use WP_Query. Info: https://wordpress.stackexchange.com/questions/50761/when-to-use-wp-query-query-posts-and-pre-get-posts/50762#50762
$show_brown_title = false;
$show_white_title = false;
$show_tomato_title = false;
$show_wine_title = false;
$show_beer_title = false;
$args = array(
'post_type' => 'drinks',
'numberposts' => '-1'
);
$query = new WP_Query( $args );
if( $query->have_posts() ):
while( $query->have_posts() ): $query->the_post();
echo '<pre>';
print_r( $query );
echo '<pre>';
endwhile;
endif;
wp_reset_postdata();
Inside the loop you will construct again your listing, use the print_r step by step, use your objects elements smart.
Aproach #2:
$show_brown_title = false;
$show_white_title = false;
$show_tomato_title = false;
$show_wine_title = false;
$show_beer_title = false;
foreach((get_the_category()) as $cat) {
$args = array(
'post_type' => 'drinks',
'numberposts' => '-1',
'cat' => $cat->cat_ID
);
$query = new WP_Query( $args );
if( $query->have_posts() ):
echo '<ul>';
while( $query->have_posts() ): $query->the_post();
echo '<h4><span>'. $query->category_name .'</span> Cocktails</h4>';
echo '<li>';
echo '<span class="drink_title">'.$query->post_title.'</span>';
echo '<span class="drink_ingredients">'.$query->drink_ingredients.'</span>';
echo '<span class="drink_price">'.$query->price_oz.'</span>';
echo '</li>';
endwhile;
echo '</ul>';
endif;
wp_reset_postdata();
}
With the specification that $query->category_name maybe should be written other way. Use print_r to see the correct field name/element of your object.
Bellow is my solution.
Note: get_posts uses the orderby parameter to order the posts by drink_category.
The code is simplified to only start <ul> when drink_category changes and to end </ul> on category change too. Code also checks that html to output has been assigned a value and appends to it a final </ul> in case one is not appended already.
$drinks = get_posts('post_type=drinks&numberposts=-1&orderby=drink_category');
$current_category = '';
$html = '';
if ( $drinks ) {
foreach( $drinks as $drink ) {
$id = $drink->ID;
$drink_location = $drink->drink_location;
if ($current_category != $drink->drink_category) {
if ($current_category != '') {
$html .= '</ul>';
}
$current_category = $drink->drink_category;
$html .= '<h4><span>' . $current_category . '</span> Cocktails</h4>';
$html .= '<ul>';
}
if($drink_location && in_array($site_slug, $drink_location)) {
$html .= '<li>';
$html .= '<span class="drink_title">'.$drink->post_title.'</span>';
$html .= '<span class="drink_ingredients">'.$drink->drink_ingredients.'</span>';
$html .= '<span class="drink_price">'.$drink->price_oz.'</span>';
$html .= '</li>';
}
}
}
if (strlen($html) > 0 && !endsWith($html, '</ul>')) {
$html .= '</ul>';
}
function endsWith($haystack, $needle)
{
$length = strlen($needle);
if ($length == 0) {
return true;
}
return (substr($haystack, -$length) === $needle);
}

Categories