debugging WC_Shipping_Method packages - wordpress

I have created an extended class out of WC_Shipping_Method and needed to debug and printout $packages in calculate_shipping method.
var_dump is not showing anything on screen. Is there anyway to display the content of such variable?
Another issue I noticed that $this->title is not changed, I run it first time and the shipment name is somehow become fixed!
function tutsplus_shipping_method() {
if ( ! class_exists( 'TutsPlus_Shipping_Method' ) ) {
class TutsPlus_Shipping_Method extends WC_Shipping_Method {
/**
* Constructor for your shipping class
*
* #access public
* #return void
*/
public function __construct() {
$this->id = 'tutsplus';
$this->method_title = __( 'TutsPlus Shipping', 'tutsplus' );
$this->method_description = __( 'Custom Shipping Method for TutsPlus', 'tutsplus' );
// Availability & Countries
$this->availability = 'including';
$this->countries = array(
'US', // Unites States of America
'CA', // Canada
'DE', // Germany
'GB', // United Kingdom
'IT', // Italy
'ES', // Spain
'HR' // Croatia
);
$this->init();
$this->enabled = isset( $this->settings['enabled'] ) ? $this->settings['enabled'] : 'yes';
$this->title = isset( $this->settings['title'] ) ? $this->settings['title'] : __( 'TutsPlus Shipping', 'tutsplus' );
}
/**
* Init your settings
*
* #access public
* #return void
*/
function init() {
// Load the settings API
$this->init_form_fields();
$this->init_settings();
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/**
* Define settings field for this shipping
* #return void
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable', 'tutsplus' ),
'type' => 'checkbox',
'description' => __( 'Enable this shipping.', 'tutsplus' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title', 'tutsplus' ),
'type' => 'text',
'description' => __( 'Title to be display on site', 'tutsplus' ),
'default' => __( 'TutsPlus Shipping', 'tutsplus' )
),
'weight' => array(
'title' => __( 'Weight (kg)', 'tutsplus' ),
'type' => 'number',
'description' => __( 'Maximum allowed weight', 'tutsplus' ),
'default' => 100
),
);
}
/**
* This function is used to calculate the shipping cost. Within this function we can check for weights, dimensions and other parameters.
*
* #access public
* #param mixed $package
* #return void
*/
public function calculate_shipping( $package ) {
$weight = 0;
$cost = 0;
$country = $package["destination"]["country"];
foreach ( $package['contents'] as $item_id => $values )
{
$_product = $values['data'];
$weight = $weight + $_product->get_weight() * $values['quantity'];
}
$weight = wc_get_weight( $weight, 'kg' );
if( $weight <= 10 ) {
$cost = 0;
} elseif( $weight <= 30 ) {
$cost = 5;
} elseif( $weight <= 50 ) {
$cost = 10;
} else {
$cost = 20;
}
$countryZones = array(
'HR' => 0,
'US' => 3,
'GB' => 2,
'CA' => 3,
'ES' => 2,
'DE' => 1,
'IT' => 1
);
$zonePrices = array(
0 => 10,
1 => 30,
2 => 50,
3 => 70
);
$zoneFromCountry = $countryZones[ $country ];
$priceFromZone = $zonePrices[ $zoneFromCountry ];
$cost += $priceFromZone;
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => $cost
);
$this->add_rate( $rate );
}
}
}
}
add_action( 'woocommerce_shipping_init', 'tutsplus_shipping_method' );
function add_tutsplus_shipping_method( $methods ) {
$methods[] = 'TutsPlus_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_tutsplus_shipping_method' );
function tutsplus_validate_order( $posted ) {
$packages = WC()->shipping->get_packages();
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
if( is_array( $chosen_methods ) && in_array( 'tutsplus', $chosen_methods ) ) {
foreach ( $packages as $i => $package ) {
if ( $chosen_methods[ $i ] != "tutsplus" ) {
continue;
}
$TutsPlus_Shipping_Method = new TutsPlus_Shipping_Method();
$weightLimit = (int) $TutsPlus_Shipping_Method->settings['weight'];
$weight = 0;
foreach ( $package['contents'] as $item_id => $values )
{
$_product = $values['data'];
$weight = $weight + $_product->get_weight() * $values['quantity'];
}
$weight = wc_get_weight( $weight, 'kg' );
if( $weight > $weightLimit ) {
$message = sprintf( __( 'Sorry, %d kg exceeds the maximum weight of %d kg for %s', 'tutsplus' ), $weight, $weightLimit, $TutsPlus_Shipping_Method->title );
$messageType = "error";
if( ! wc_has_notice( $message, $messageType ) ) {
wc_add_notice( $message, $messageType );
}
}
}
}
}
add_action( 'woocommerce_review_order_before_cart_contents', 'tutsplus_validate_order' , 10 );
add_action( 'woocommerce_after_checkout_validation', 'tutsplus_validate_order' , 10 );

Related

Woocommerce get custom min price of variable products

I am trying to get a custom min price excluding some of the attribute values that contain the words lid and deckel but I am getting a fatal error. Can anyone please help with this?
add_filter( 'woocommerce_variable_price_html', 'bbloomer_variation_price_format', 10, 2 );
function bbloomer_variation_price_format( $price, $product ) {
$args = array(
'post_status' => 'publish',
'post_type' => 'product',
'meta_query' => array(
array(
'key' => 'pa_option',
'value' => array(Deckel),
'compare' => 'NOT LIKE',
)
)
);
}
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$min_var_reg_price = $product->get_variation_regular_price( 'min', true );
$min_var_sale_price = $product->get_variation_sale_price( 'min', true );
$max_var_reg_price = $product->get_variation_regular_price( 'max', true );
$max_var_sale_price = $product->get_variation_sale_price( 'max', true );
if ( ! ( $min_var_reg_price == $max_var_reg_price && $min_var_sale_price == $max_var_sale_price ) ) {
if ( $min_var_sale_price < $min_var_reg_price ) {
$price = sprintf( __( 'ab <del>%s</del><ins>%s</ins> %s', 'woocommerce' ), wc_price( $min_var_reg_price ), wc_price( $min_var_sale_price ), $product->get_price_suffix() );
} else {
$price = sprintf( __( 'ab %s %s', 'woocommerce' ), wc_price( $min_var_reg_price ), $product->get_price_suffix() );
}
}
return $price;
}
}

update the price of a selected product variant in woocommerce sql

I need to make changes to the code that calculates prices for a large number of variants of one product according to the set price calculation logic
How to change the code below to:
all variants in white would have a price calculated according to "$price1 = round (... calculations ...);.
and variants in black would have a price calculated according to $price2 = round (... calculations ...);
<?php
(...)
$config = [
'product_id' => 123,
'attributes_values' => [
(...)
'attribute_pa_color' => [
'white' => 1,
'black' => 2,
]
]
];
$product_variations = $wpdb->get_results("SELECT * FROM `wp_posts` WHERE `post_parent` = ".$config['product_id']." AND `post_type` LIKE 'product_variation'");
if( $product_variations ){
foreach( $product_variations as $product_variation ){
$pva = [];
$product_variation_attributes_dba = $wpdb->get_results("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$product_variation->ID." AND `meta_key` LIKE 'attribute_pa_%'");
if ( $product_variation_attributes_dba ) foreach( $product_variation_attributes_dba as $prod_attr){
$value = $config['attributes_values'][$prod_attr->meta_key][$prod_attr->meta_value];
if( !empty( $config['attributes_values'][$prod_attr->meta_key] ) ){
if( !$value>0 ){
echo 'Błąd przy parsowaniu produktu #'.$product_variation->ID.' ('.$prod_attr->meta_key.' = '.$prod_attr->meta_value.')<br>';
exit;
}
$pva[ $prod_attr->meta_key ] = $value;
}
}
$price1 = round( ...calculations... );
$price2 = round( ...calculations... );
$regular_price = $wpdb->get_row("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$product_variation->ID." AND `meta_key` LIKE '_regular_price'");
if($regular_price){
$wpdb->update( 'wp_postmeta', array( 'meta_value'=> $price ), array( 'post_id' => $product_variation->ID, 'meta_key' => '_regular_price' ) ,array( '%s', '%s', '%d', ) );
}else{
$wpdb->insert( 'wp_postmeta', array( 'post_id' => $product_variation->ID, 'meta_key' => '_regular_price', 'meta_value'=> $price ), array( '%s', '%s', '%d', ) );
}
$regular_price = $wpdb->get_row("SELECT * FROM `wp_postmeta` WHERE `post_id` = ".$product_variation->ID." AND `meta_key` LIKE '_price'");
if($regular_price){
$wpdb->update( 'wp_postmeta', array( 'meta_value'=> $price ), array( 'post_id' => $product_variation->ID, 'meta_key' => '_price' ) ,array( '%s', '%s', '%d', ) );
}else{
$wpdb->insert( 'wp_postmeta', array( 'post_id' => $product_variation->ID, 'meta_key' => '_price', 'meta_value'=> $price ), array( '%s', '%s', '%d', ) );
}
$_thumbnail_id = $pva['attribute_pa_color']==2?4333:4278;
$wpdb->update( 'wp_postmeta', array( 'meta_value'=> $_thumbnail_id ), array( 'post_id' => $product_variation->ID, 'meta_key' => '_thumbnail_id' ) ,array( '%s', '%s', '%d', ) );
}
}
echo 'Successful price import!';

Woocommerce update order value after updating cart discount

I want to add maximum discount limit on % discount coupons. I've added this code to do so in cart, but payment gateway is still getting the % discount without the maximum limit set by this code. Will I have to update any other value to fix this?
Payment gateway plugging is getting the total using get_total method.
add_action( 'woocommerce_coupon_options_usage_limit', 'woocommerce_coupon_options_usage_limit', 10, 2 );
function woocommerce_coupon_options_usage_limit( $coupon_id, $coupon )
{
echo '';
// max discount per coupons
$max_discount = get_post_meta( $coupon_id, '_max_discount', true );
woocommerce_wp_text_input( array(
'id' => 'max_discount',
'label' => __( 'Usage max discount', 'woocommerce' ),
'placeholder' => esc_attr( $max_discount, 'woocommerce' ),
'description' => __( 'The maximum discount this coupon can give.', 'woocommerce' ),
'type' => 'number',
'desc_tip' => true,
'class' => 'short',
'custom_attributes' => array(
'step' => 1,
'min' => 0,
),
'value' => $max_discount ? $max_discount : '',
) );
echo '';
}
add_action( 'woocommerce_coupon_options_save', 'woocommerce_coupon_options_save', 10, 2 );
function woocommerce_coupon_options_save( $coupon_id, $coupon ) {
update_post_meta( $coupon_id, '_max_discount', wc_format_decimal( $_POST['max_discount'] ) );
}
// filter to change discount if over max coupon amount
function filter_woocommerce_coupon_get_discount_amount( $discount, $discounting_amount, $cart_item, $single, $instance ) {
$cartCoupons = WC()->cart->get_applied_coupons();
foreach ($cartCoupons as $key => $appliedCoupon) {
$coupon = new WC_Coupon($appliedCoupon);
$couponType = get_post_meta( $coupon->get_id(), 'discount_type', true );
if ($couponType == 'percent') {
$maxCouponAmount = get_post_meta( $coupon->get_id(), '_max_discount', true );
$excludedProducts = explode(",", get_post_meta( $coupon->get_id(), 'exclude_product_ids', true ));
$cartLines = count(WC()->cart->get_cart());
$cartLineItems = WC()->cart->get_cart();
foreach ($cartLineItems as $cartItem){
$cartProductID[] = $cartItem['product_id'];
if (!empty($excludedProducts)) {
$cartLinesWithoutExcluded = array_intersect($cartProductID,$excludedProducts);
} else {
$cartLinesWithoutExcluded = $cartProductID;
}
$cartLinesWithoutExcluded = count($cartLinesWithoutExcluded);
$totalCartItems = $cartLines - $cartLinesWithoutExcluded;
$discount = $maxCouponAmount / $totalCartItems;
}
} else {
$discount = 0.00;
}
return $discount;
}
}
// apply the coupon whether it is max discount or a product price adjustment
function apply_max_amount_or_product_price_adjustment(){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
if ( !is_admin() && !wp_is_json_request() ) {
global $wp, $woocommerce, $post;
$cartCoupons = WC()->cart->get_applied_coupons();
foreach ($cartCoupons as $key => $appliedCoupon) {
$coupon = new WC_Coupon($appliedCoupon);
$maxCouponAmount = get_post_meta( $coupon->get_id(), '_max_discount', true );
$excludedProducts = explode(",", get_post_meta( $coupon->get_id(), 'exclude_product_ids', true ));
$couponType = get_post_meta( $coupon->get_id(), 'discount_type', true );
// $fixedProductPrice = get_post_meta( $coupon->get_id(), '_adjust_price', true );
$couponAmount = WC()->cart->get_coupon_discount_amount( $appliedCoupon );
if (!empty($maxCouponAmount) && $couponType == 'percent' && ($couponAmount >= $maxCouponAmount)) {
$couponAmount = add_filter( 'woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5 );
}
if ($couponType == 'fixed_cart') {
$cart = WC()->cart->get_cart();
$couponProducts = explode(',',get_post_meta( $coupon->get_id(), 'product_ids', true ));
$fixedPricePerProduct = get_post_meta( $coupon->get_id(), '_price_per_product_amt', true );
foreach( $cart as $cart_item ) {
if (in_array($cart_item['data']->get_parent_id(), $couponProducts)) {
$cart_item['data']->set_price( $fixedPricePerProduct );
}
}
}
}
}
}
add_action('woocommerce_before_calculate_totals', 'apply_max_amount_or_product_price_adjustment', 10, 1);
add_action('woocommerce_coupon_options_usage_limit', 'woocommerce_coupon_options_usage_limit', 10, 2);
function woocommerce_coupon_options_usage_limit($coupon_id, $coupon)
{
echo '';
// max discount per coupons
$max_discount = get_post_meta($coupon_id, '_max_discount', true);
woocommerce_wp_text_input(array(
'id' => 'max_discount',
'label' => __('Usage max discount', 'woocommerce'),
'placeholder' => esc_attr($max_discount, 'woocommerce'),
'description' => __('The maximum discount this coupon can give.', 'woocommerce'),
'type' => 'number',
'desc_tip' => true,
'class' => 'short',
'custom_attributes' => array(
'step' => 1,
'min' => 0,
),
'value' => $max_discount ? $max_discount : '',
));
echo '';
}
add_action('woocommerce_coupon_options_save', 'woocommerce_coupon_options_save', 10, 2);
function woocommerce_coupon_options_save($coupon_id, $coupon)
{
update_post_meta($coupon_id, '_max_discount', wc_format_decimal($_POST['max_discount']));
}
// filter to change discount if over max coupon amount
function filter_woocommerce_coupon_get_discount_amount($discount, $discounting_amount, $cart_item, $single, $instance)
{
$cartCoupons = WC()->cart->get_applied_coupons();
foreach ($cartCoupons as $key => $appliedCoupon) {
$coupon = new WC_Coupon($appliedCoupon);
$couponType = get_post_meta($coupon->get_id(), 'discount_type', true);
if ($couponType == 'percent') {
$maxCouponAmount = get_post_meta($coupon->get_id(), '_max_discount', true);
$excludedProducts = explode(",", get_post_meta($coupon->get_id(), 'exclude_product_ids', true));
$cartLines = count(WC()->cart->get_cart());
$cartLineItems = WC()->cart->get_cart();
foreach ($cartLineItems as $cartItem) {
$cartProductID[] = $cartItem['product_id'];
if (!empty($excludedProducts)) {
$cartLinesWithoutExcluded = array_intersect($cartProductID, $excludedProducts);
} else {
$cartLinesWithoutExcluded = $cartProductID;
}
$cartLinesWithoutExcluded = count($cartLinesWithoutExcluded);
$totalCartItems = $cartLines - $cartLinesWithoutExcluded;
$new_discount = $maxCouponAmount / $totalCartItems;
if ($new_discount < $discount) {
$discount = $new_discount;
}
}
} else {
$discount = 0.00;
}
return $discount;
}
}
// apply the coupon whether it is max discount or a product price adjustment
function apply_max_amount_or_product_price_adjustment()
{
if (is_admin() && !defined('DOING_AJAX'))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
if (!is_admin() && !wp_is_json_request()) {
global $wp, $woocommerce, $post;
$cartCoupons = WC()->cart->get_applied_coupons();
foreach ($cartCoupons as $key => $appliedCoupon) {
$coupon = new WC_Coupon($appliedCoupon);
$maxCouponAmount = get_post_meta($coupon->get_id(), '_max_discount', true);
$excludedProducts = explode(",", get_post_meta($coupon->get_id(), 'exclude_product_ids', true));
$couponType = get_post_meta($coupon->get_id(), 'discount_type', true);
// $fixedProductPrice = get_post_meta( $coupon->get_id(), '_adjust_price', true );
$couponAmount = WC()->cart->get_coupon_discount_amount($appliedCoupon);
if (!empty($maxCouponAmount) && $couponType == 'percent' && ($couponAmount >= $maxCouponAmount)) {
$couponAmount = add_filter('woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5);
}
if ($couponType == 'fixed_cart') {
$cart = WC()->cart->get_cart();
$couponProducts = explode(',', get_post_meta($coupon->get_id(), 'product_ids', true));
$fixedPricePerProduct = get_post_meta($coupon->get_id(), '_price_per_product_amt', true);
foreach ($cart as $cart_item) {
if (in_array($cart_item['data']->get_parent_id(), $couponProducts)) {
$cart_item['data']->set_price($fixedPricePerProduct);
}
}
}
}
}
}
add_action('woocommerce_before_calculate_totals', 'apply_max_amount_or_product_price_adjustment', 10, 1);
add_filter('woocommerce_coupon_get_discount_amount', 'filter_woocommerce_coupon_get_discount_amount', 10, 5);

add rewrite rule custom post type

I've been working on this for 4 days now and can't figure out what I'm missing. I have searched and tried everything that comes up for wp rewriting.
It works but doesn't save. So if I go to quick edit and save, click view it works. If I refresh and hover over view %property_type% is missing and doesn't work.
Any Idea what I'm missing?
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_admin_column' => true,
'query_var' => true,
'rewrite' => array(
'slug' => str_replace( basename( home_url() ), '', 'investment-property' ) . '/%property_type%',
'with_front' => false
),
'capability_type' => 'page',
'has_archive' => true,
'hierarchical' => true,
'comment_status'=> 'closed',
'exclude_from_search' =>false,
'supports' => array('title', 'editor', 'thumbnail'),
);
register_post_type( 'property', $args );
I also have this...
function my_flush_rules() {
$rules = get_option( 'rewrite_rules' );
if ( ! isset( $rules['(investment-property/%property_type%/)/(.+)$'] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
}
...and this
function icn_property_type_link( $permalink, $post, $leavename ) {
global $wp_query, $wpsc_page_titles, $wp_rewrite, $wp_current_filter;
$rewritecode = array(
'%property_type%',
$leavename ? '' : '%postname%',
);
if ( is_object( $post ) ) {
// In wordpress 2.9 we got a post object
$post_id = $post->ID;
} else {
// In wordpress 3.0 we get a post ID
$post_id = $post;
$post = get_post( $post_id );
}
// Only applies to ICN properties, don't stop on permalinks of other CPTs
if ($post->post_type != 'property')
return $permalink;
$permalink_structure = get_option( 'permalink_structure' );
// This may become customize-able later
$our_permalink_structure = str_replace( basename( home_url() ), '', 'investment-property' ) . "/%property_type%/%postname%/";
// Mostly the same conditions used for posts, but restricted to items with a post type of "wpsc-product "
if ( '' != $permalink_structure && !in_array( $post->post_status, array( 'draft', 'pending' ) ) ) {
$property_categories = get_the_terms($post_id, 'property_type' );
$property_category_slugs = array( );
foreach ( $property_categories as $property_category ) {
if($property_category->slug == 'featured'){continue;}
$property_category_slugs[] = $property_category->slug;
}
// If the property is associated with multiple categories, determine which one to pick
if ( count( $property_categories ) == 0 || $property_categories == '') {
$category_slug = 'real-estate-for-sale';
} elseif ( count( $property_categories ) > 1 ) {
if ( (isset( $wp_query->query_vars['property'] ) && $wp_query->query_vars['property'] != null) && in_array( $wp_query->query_vars['property'], $property_category_slugs ) ) {
$property_category = $wp_query->query_vars['property'];
} else {
$link = $property_categories[0]->slug;
if ( ! in_array( 'wp_head', $wp_current_filter) && isset( $wp_query->query_vars['property_type'] ) ) {
$current_cat = $wp_query->query_vars['property_type'];
if ( in_array( $current_cat, $property_category_slugs ) ){
$link = $current_cat;
}
}
$property_category = $link;
}
$category_slug = $property_category;
} else {
// If the property is associated with only one category, we only have one choice
if ( !isset( $property_categories[0] ) )
$property_categories[0] = '';
$property_category = $property_categories[0];
if ( !is_object( $property_category ) )
$property_category = new stdClass();
if ( !isset( $property_category->slug ) )
$property_category->slug = null;
$category_slug = $property_category->slug;
}
$post_name = $post->post_name;
if ( get_option( 'property_type_hierarchical_url', 0 ) ) {
$selected_term = get_term_by( 'slug', $category_slug, 'property_type' );
if ( is_object( $selected_term ) ) {
$term_chain = array( $selected_term->slug );
while ( $selected_term->parent ) {
$selected_term = get_term( $selected_term->parent, 'property_type' );
array_unshift( $term_chain, $selected_term->slug );
}
$category_slug = implode( '/', $term_chain );
}
}
if( isset( $category_slug ) && empty( $category_slug ) )
$category_slug = 'property_type';
$category_slug = apply_filters( 'property_type_permalink_cat_slug', $category_slug, $post_id );
$rewritereplace = array(
$category_slug,
$post_name
);
$permalink = str_replace( $rewritecode, $rewritereplace, $our_permalink_structure );
$permalink = user_trailingslashit( $permalink, 'single' );
$permalink = home_url( $permalink );
}
return apply_filters( 'property_permalink', $permalink, $post_id );
}
add_filter( 'post_type_link', 'icn_property_type_link', 1, 3 );

Adding weighted tags in wordpress

Is there a way I can add weighted tags to wordpress? I need to customize the tag cloud widget to show the most used tags with different colors
I've stumbled upon this as well. Here's a modified function from the original tag cloud widget:
<?php
function my_colorful_tag_cloud( $args = array() ) {
$defaults = array(
'smallest' => 10, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC',
'exclude' => '', 'include' => '', 'link' => 'view', 'taxonomy' => 'post_tag', 'echo' => true
);
$args = wp_parse_args( $args, $defaults );
$tags = get_terms( $args['taxonomy'], array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) ); // Always query top tags
if ( empty( $tags ) || is_wp_error( $tags ) )
return;
foreach ( $tags as $key => $tag ) {
$link = get_term_link( intval($tag->term_id), $tag->taxonomy );
if ( is_wp_error( $link ) )
return false;
$tags[ $key ]->link = $link;
$tags[ $key ]->id = $tag->term_id;
}
$defaults = array(
'smallest' => 10, 'largest' => 22, 'unit' => 'pt', 'number' => 0,
'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC',
'topic_count_text_callback' => 'default_topic_count_text',
'topic_count_scale_callback' => 'default_topic_count_scale', 'filter' => 1,
);
if ( !isset( $args['topic_count_text_callback'] ) && isset( $args['single_text'] ) && isset( $args['multiple_text'] ) ) {
$body = 'return sprintf (
_n(' . var_export($args['single_text'], true) . ', ' . var_export($args['multiple_text'], true) . ', $count),
number_format_i18n( $count ));';
$args['topic_count_text_callback'] = create_function('$count', $body);
}
$args = wp_parse_args( $args, $defaults );
extract( $args );
if ( empty( $tags ) )
return;
$tags_sorted = apply_filters( 'tag_cloud_sort', $tags, $args );
if ( $tags_sorted != $tags ) { // the tags have been sorted by a plugin
$tags = $tags_sorted;
unset($tags_sorted);
} else {
if ( 'RAND' == $order ) {
shuffle($tags);
} else {
// SQL cannot save you; this is a second (potentially different) sort on a subset of data.
if ( 'name' == $orderby )
uasort( $tags, '_wp_object_name_sort_cb' );
else
uasort( $tags, '_wp_object_count_sort_cb' );
if ( 'DESC' == $order )
$tags = array_reverse( $tags, true );
}
}
if ( $number > 0 )
$tags = array_slice($tags, 0, $number);
$counts = array();
$real_counts = array(); // For the alt tag
foreach ( (array) $tags as $key => $tag ) {
$real_counts[ $key ] = $tag->count;
$counts[ $key ] = $topic_count_scale_callback($tag->count);
}
$min_count = min( $counts );
$spread = max( $counts ) - $min_count;
if ( $spread <= 0 )
$spread = 1;
$font_spread = $largest - $smallest;
if ( $font_spread < 0 )
$font_spread = 1;
$font_step = $font_spread / $spread;
$a = array();
$colors = 6;
foreach ( $tags as $key => $tag ) {
$count = $counts[ $key ];
$real_count = $real_counts[ $key ];
$tag_link = '#' != $tag->link ? esc_url( $tag->link ) : '#';
$tag_id = isset($tags[ $key ]->id) ? $tags[ $key ]->id : $key;
$tag_name = $tags[ $key ]->name;
$class = 'color-' . ( round( ( $smallest + ( ( $count - $min_count ) * $font_step ) ) - ( $smallest - 1 ) ) );
$a[] = "<a href='$tag_link' class='tag-link-$tag_id $class' title='" . esc_attr( call_user_func( $topic_count_text_callback, $real_count ) ) . "' style='font-size: " .
str_replace( ',', '.', ( $smallest + ( ( $count - $min_count ) * $font_step ) ) )
. "$unit;'>$tag_name</a>";
}
$return = join( $separator, $a );
return apply_filters( 'wp_generate_tag_cloud', $return, $tags, $args );
}
This code (by default)will generate a tag cloud with 13 possible classes for each tag(since the defaults are min. size=10 and max.size = 22). In order to change the color for each tag weight, simply add those rules to your CSS:
.colorful_tag_cloud a.color-x { color: {color} }
where "x" is a number from 1 to 13
Hope this helps.

Resources