I have a problem on the "my account" page of my woocommerce store.
Indeed, when I log in with a new customer account that has never placed an order, I have 3 content containers that disappear.
After testing, they only appear if I place an order with the account in question.
Do you have any idea where this could be coming from?
The 3 divs in question correspond to :
the navigation menu of the page my account that disappears only on the dashboard tab (it reappears on all other tabs - my orders, my addresses ...)
a div with the recently viewed products (see code n°1 below)
a div with the articles recently written by the customer (see code n°2 below)
When an order is placed, all the content reappears.
I also have a div with the recent orders which strangely, does not have any problem of display (see code n°3 below)
Do not hesitate to ask me for clarifications, or if you think that the error comes from a tag elsewhere in my code (a tag of authorization according to the role for example?)
In advance, Thank you very much for your help.
add_shortcode( 'recently_viewed_products', 'bbloomer_recently_viewed_shortcode' );
function bbloomer_recently_viewed_shortcode() {
$viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) : array();
$viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );
if ( empty( $viewed_products ) ) return;
?>
<div class="col-23">
<?php $title = '<h3>Produits consultés récemment</h3>';?>
<?php $product_ids = implode( ",", $viewed_products );?>
<?php return $title . do_shortcode("[products ids='$product_ids' limit='4' columns='4' orderby='post__in' class='recentes-vues']");?>
</div>
<?php }
function custom_track_product_view() {
if ( ! is_singular( 'product' ) ) {
return;
}
global $post;
if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) )
$viewed_products = array();
else
$viewed_products = (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] );
if ( ! in_array( $post->ID, $viewed_products ) ) {
$viewed_products[] = $post->ID;
}
if ( sizeof( $viewed_products ) > 15 ) {
array_shift( $viewed_products );
}
// Store for session only
wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}
add_action( 'template_redirect', 'custom_track_product_view', 20 );
// PRODUIT RECENT PAGE COMPTE
add_action( 'woocommerce_account_dashboard' , 'recentes_vues', 5 );
function recentes_vues() {
echo do_shortcode('[recently_viewed_products]');
}
add_action( 'woocommerce_account_dashboard' , 'recent_posts', 3 );
function recent_posts() {
if ( is_user_logged_in()) :
global $current_user;
wp_get_current_user();
$author_query = array('posts_per_page' => '-1','author' => $current_user->ID);
$author_posts = new WP_Query($author_query);
?><div id="recentposts">
<?php
if ($author_posts->found_posts) {
?>
<ul class="liststylenone">
<?php
while($author_posts->have_posts()) : $author_posts->the_post();
?>
<li><?php the_title(); ?></li>
<?php
endwhile;
?></ul><?php
}
else {
echo '<p>Aucun article trouvé 😞</p>';
}
else :
echo "not logged in";
endif;
?>
add_action( 'woocommerce_account_dashboard', 'recent_order', 2 );
function recent_order(){
// For logged in users only
if ( is_user_logged_in() ) :
$user_id = get_current_user_id(); // The current user ID
// Get the WC_Customer instance Object for the current user
$customer = new WC_Customer( $user_id );
// Get the last WC_Order Object instance from current customer
$last_order = $customer->get_last_order();
if ( is_a( $last_order, 'WC_Order' ) ) {
$order_id = $last_order->get_id(); // Get the order id
$order_data = $last_order->get_data(); // Get the order unprotected data in an array
$order_status = $last_order->get_status(); // Get the order status
$date_created = $last_order->get_date_created();
$order_total = $last_order->get_total();
}
?>
<div class="row last-order">
<div class="col-md-7">
<div class="col-3">
<div class="col-5">
<div class="col-md-4 order-status-box">
<h6 class="status">État : <?php echo esc_html( wc_get_order_status_name( $order_status ) ); ?></h6>
</div>
<p class="totalcmdd"><?php echo $order_total."€"; ?></p>
<?php
setlocale(LC_TIME, 'fr_FR');
date_default_timezone_set('Europe/Paris');
echo utf8_encode(strftime('%d %B %Y', strtotime($date_created)));
//echo date('d-F-Y', strtotime($date_created)); ?>
</p>
</div>
<div style="display: flex;flex-direction: row;justify-content: space-evenly;align-items: center;margin-right: 1.5em;margin-left: 1.5em;padding: 0.3em;background-color: white;text-transform: uppercase;text-decoration: none;font-size: 13px;">
<?php foreach ($last_order->get_items() as $item) :
$product = $item->get_product();
$thumbnail = $product->get_image(array(50, 50));
if ($product->get_image_id() > 0) {
$item_name = '<div class="item-thumbnail">' . $thumbnail . '</div>'; // You had an extra variable here
}
echo $item_name . $item->get_name();
endforeach;
endif;
?>
Related
Can someone help me how can i fix this code
instead of showing the country it shows the author
can you guys tell me what i did wrong on this code?
add_action( 'woocommerce_after_shop_loop_item_title','sold_by' );
function sold_by(){
?>
<?php
global $product;
$seller = get_post_field( 'post_author', $product->get_id());
$author = get_user_by( 'id', $seller );
$store_info = dokan_get_store_info( $author->ID );
$address = dokan_get_store_info( $author->address );
?>
<span class="details">
<?php printf( 'Origin: %s', $author->display_name, $address ); ?>
</span>
<?php
}
See this screenshot showing origin as author instead of country:
Try the following :
add_action( 'woocommerce_after_shop_loop_item_title','dokan_store_country' );
function dokan_store_country(){
global $product;
$seller_id = get_post_field( 'post_author', $product->get_id());
$seller = new WP_User( $seller_id );
$countries = WC()->countries->get_countries();
$store_data = dokan_get_store_info( seller_id );
if ( isset( $store_data['country'] ) ) {
$store_country = $store_data['country']; // Try to get seller store country
} elseif( isset( $countries[$seller->billing_country] ) ) {
$store_country = $countries[$seller->billing_country]; // Try to get seller billing country
} else {
return; // Exit
}
echo '<span class="details">' . sprintf( __('Origin: %s'), $store_country ) . '</span>';
}
Untested, it could work.
I've added the following snippet to display a custom field (that don't display taxonomy field if product has field) with the estimated delivery time. This is working.
<?php add_action( 'woocommerce_before_add_to_cart_form', 'geschatte_levertijd', 10 );
function geschatte_levertijd (){
if( get_field('plevertijd') ): ?>
<span class="product_melding_kleur"><i class="fa fa-truck"></i>Levertijd: <a href="/verzending-en-levertijd/" alt="Verzending en levertijd" ><?php the_field( 'plevertijd' ); ?></a></span>
<?php else: ?>
<? $terms = get_the_terms( $post->ID, 'product_cat' );
if ( !empty($terms)):
$term = array_pop($terms);
$text= get_field('levertijd', $term);
if (!empty($levertijd))?>
<span class="product_melding_kleur"><i class="fa fa-truck"></i>Levertijd: <a href="/verzending-en-levertijd/" alt="Verzending en levertijd" ><?php the_field( 'levertijd', $term ); ?></a></span>
<?php endif; ?>
<?php endif;
}
?>
But now I'm trying to display that field inside the order notification mail. Below the product title.
Could someone point me into the right direction on how to do that?
The following will use your code to make happen the display in order email notifications under order item product name:
add_action( 'woocommerce_order_item_meta_start', 'add_estimated_delivery_time_to_emails', 10, 3 );
function add_estimated_delivery_time_to_emails( $item_id, $item, $order ) {
// On email notifications and for line items
if ( ! is_wc_endpoint_url() && $item->is_type('line_item') ) {
if( $plevertijd = get_field('plevertijd', $item->get_product_id() ) ) {
echo '<span class="product_melding_kleur"><i class="fa fa-truck"></i>Levertijd: <a href="/verzending-en-levertijd/" alt="Verzending en levertijd" >' . $plevertijd . '</a></span>';
} else {
$terms = get_the_terms( $item->get_product_id(), 'product_cat' );
if ( ! empty($terms) ) {
$term = array_pop( $terms );
if( $levertijd = get_field('levertijd', $term ) ) {
echo '<span class="product_melding_kleur"><i class="fa fa-truck"></i>Levertijd: <a href="/verzending-en-levertijd/" alt="Verzending en levertijd" >' . $levertijd . '</a></span>';
}
}
}
}
}
Code goes in functions.php file of your active child theme (or active theme). It should works.
Displaying on frontend orders:
If you want that to be displayed on customer order (front end), you can remove from the IF statement the following: ! is_wc_endpoint_url() &&
You can also use the woocommerce_order_item_meta_end hook instead, to get the display after the product attributes on product variations.
I'm using woocommerce for my website, but as I only have one main product and two accessories (related products), I don't need a classic shop page, neither single-product pages for each of my product. My main product has a color variation.
I want to have an add-to-cart button, with the color variation dropdown and the quantity field in one of my regular post page. Exactly like on a single-product page, but embedded in my own page, and without the parts of the single-product page I don't need (description, ...).
I finally decided to achieve this using two custom shortcodes I created: [my_vc_product_price id="xxx"] and [my_vc_add2cart_variable_product id="xxx"]. So I can put them where I want.
But my problem is that the behavior of the dropdown menu + variation availability + add-to-cart button is not the same that this elements have in the single-product page:
- the availability of he variation doesn't show up when I choose the color in the dropdown menu;
- the add-to-cart button is not disable when no color is chosen in the dropdown menu (it should be disable and active only when a color is chosen).
Displaying the price was easy, using some code found on internet:
/**
* Add shortcode to allow to display product price in a page
*/
function my_vc_display_product_price( $args ) {
$product_id = $args['id'];
$product = wc_get_product( $product_id );
echo '<p class="price">' . $product->get_price_html() . '</p>';
}
add_shortcode( 'my_vc_product_price', 'my_vc_display_product_price');
To get the same graphical result, I just had to add some CSS classes on the row: "woocommerce" and "product".
The code to display the dropdown menu + the quantity and the add-to-cart button is almost the same than in the variable.php file found in plugins/woocommerce/templates/single-product/add-to-cart/. The only things really change is that you need to get the "variation attributes" of the product, and not the attributes.
$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
So the full function code is:
/**
* Add shortcode to allow to display an add to cart button with dropdown menu for variation attributes
*/
function my_vc_add_to_cart_button_variable_product( $args ) {
global $product;
$product_id = $args['id'];
$product = wc_get_product( $product_id );
if( $product->is_type( 'variable' )) {
$attributes = $product->get_variation_attributes();
$attribute_keys = array_keys( $attributes );
$available_variations = array( $product->get_available_variations() );
do_action( 'woocommerce_before_add_to_cart_form' ); ?>
<form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint( $product->get_id() ); ?>" data-product_variations="<?php echo htmlspecialchars( wp_json_encode( $available_variations ) ) ?>">
<?php do_action( 'woocommerce_before_variations_form' ); ?>
<?php if ( empty( $available_variations ) && false !== $available_variations ) : ?>
<p class="stock out-of-stock"><?php _e( 'This product is currently out of stock and unavailable.', 'woocommerce' ); ?></p>
<?php else : ?>
<table class="variations" cellspacing="0">
<tbody>
<?php foreach ( $attributes as $attribute_name => $options ) : ?>
<tr>
<td class="value">
<?php
$selected = isset( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ? wc_clean( stripslashes( urldecode( $_REQUEST[ 'attribute_' . sanitize_title( $attribute_name ) ] ) ) ) : $product->get_variation_default_attribute( $attribute_name );
wc_dropdown_variation_attribute_options( array( 'options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected ) );
?>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<?php do_action( 'woocommerce_before_add_to_cart_button' ); ?>
<div class="single_variation_wrap">
<?php
/**
* woocommerce_before_single_variation Hook.
*/
do_action( 'woocommerce_before_single_variation' );
/**
* woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
* #since 2.4.0
* #hooked woocommerce_single_variation - 10 Empty div for variation data.
* #hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
*/
do_action( 'woocommerce_single_variation' );
?>
<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">{{{ data.variation.variation_description }}}</div>
<div class="woocommerce-variation-price">{{{ data.variation.price_html }}}</div>
<div class="woocommerce-variation-availability">{{{ data.variation.availability_html }}}</div>
</script>
<script type="text/template" id="tmpl-unavailable-variation-template">
<p><?php _e( 'Sorry, this product is unavailable. Please choose a different combination.', 'woocommerce' ); ?></p>
</script>
<?php
/**
* woocommerce_after_single_variation Hook.
*/
do_action( 'woocommerce_after_single_variation' );
?>
</div>
<?php do_action( 'woocommerce_after_add_to_cart_button' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_after_variations_form' ); ?>
</form>
<?php
do_action( 'woocommerce_after_add_to_cart_form' );
}
}
add_shortcode( 'my_vc_add2cart_variable_product', 'my_vc_add_to_cart_button_variable_product');
Any idea what is going wrong? I don't understand, if the code is the same, why it didn't execute the same. Is there something missing because this code is outside woocommerce pages?
try using following code
function add_to_cart_form_shortcode( $atts ) {
if ( empty( $atts ) ) {
return '';
}
if ( ! isset( $atts['id'] ) && ! isset( $atts['sku'] ) ) {
return '';
}
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
);
if ( isset( $atts['sku'] ) ) {
$args['meta_query'][] = array(
'key' => '_sku',
'value' => sanitize_text_field( $atts['sku'] ),
'compare' => '=',
);
$args['post_type'] = array( 'product', 'product_variation' );
}
if ( isset( $atts['id'] ) ) {
$args['p'] = absint( $atts['id'] );
}
$single_product = new WP_Query( $args );
$preselected_id = '0';
if ( isset( $atts['sku'] ) && $single_product->have_posts() && 'product_variation' === $single_product->post->post_type ) {
$variation = new WC_Product_Variation( $single_product->post->ID );
$attributes = $variation->get_attributes();
$preselected_id = $single_product->post->ID;
$args = array(
'posts_per_page' => 1,
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'no_found_rows' => 1,
'p' => $single_product->post->post_parent,
);
$single_product = new WP_Query( $args );
?>
<script type="text/javascript">
jQuery( document ).ready( function( $ ) {
var $variations_form = $( '[data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>"]' ).find( 'form.variations_form' );
<?php foreach ( $attributes as $attr => $value ) { ?>
$variations_form.find( 'select[name="<?php echo esc_attr( $attr ); ?>"]' ).val( '<?php echo esc_js( $value ); ?>' );
<?php } ?>
});
</script>
<?php
}
$single_product->is_single = true;
ob_start();
global $wp_query;
$previous_wp_query = $wp_query;
$wp_query = $single_product;
wp_enqueue_script( 'wc-single-product' );
while ( $single_product->have_posts() ) {
$single_product->the_post()
?>
<div class="single-product" data-product-page-preselected-id="<?php echo esc_attr( $preselected_id ); ?>">
<?php woocommerce_template_single_add_to_cart(); ?>
</div>
<?php
}
$wp_query = $previous_wp_query;
wp_reset_postdata();
return '<div class="woocommerce">' . ob_get_clean() . '</div>';
}
add_shortcode( 'add_to_cart_form', 'add_to_cart_form_shortcode' );
/*Example Usage [add_to_cart_form id=147]*/
That's just perfect! Many thanks.
Now the hardest to come: I need to understand your code and compare it with mine ;-)
I am trying to add some functionality to woocommerce as per a clients request. The functionality involves me having to modify woocommerce source code. I have explained to the client why this is a bad idea, however they insist, so I do it.
But I am having some trouble adding some values to POST.
This is all done from the woocommerce backend >> orders.
Essentially I am adding a width and height to a product that is added via the back-end by a shop admin.
The only problem that I have is getting the width and height into POST.
I have this code: (backbone modal popup)
<script type="text/template" id="wc-modal-add-products">
<div class="wc-backbone-modal">
<div class="wc-backbone-modal-content">
<section class="wc-backbone-modal-main" role="main">
<header class="wc-backbone-modal-header">
<a class="modal-close modal-close-link" href="#"><span class="close-icon"><span class="screen-reader-text">Close media panel</span></span></a>
<h1><?php _e( 'Add products', 'woocommerce' ); ?></h1>
</header>
<article style="min-height:70px;">
<form action="" method="post">
<input type="hidden" id="add_item_id" name="add_order_items" class="wc-product-search" style="width: 100%;" data-placeholder="<?php _e( 'Search for a product…', 'woocommerce' ); ?>" data-multiple="true" />
<input name="wpti_x" placeholder="Width" class="wpti-product-size" id="wpti-product-x" type="number">
<input name="wpti_y" placeholder="Height" class="wpti-product-size" id="wpti-product-y" type="number">
</form>
</article>
<footer>
<div class="inner">
<button id="btn-ok" class="button button-primary button-large"><?php _e( 'Add', 'woocommerce' ); ?></button>
</div>
</footer>
</section>
</div>
</div>
<div class="wc-backbone-modal-backdrop modal-close"> </div>
</script>
and this is the PHP which controls the data:
<?php
public static function add_order_item() {
function new_prices($backend_prod_id){
$pluginpath = "/home/#####/wp-content/plugins/codecanyon-7104096-woo-table-based-pricing/";
include_once $pluginpath . 'woocommerce-price-table.php';
$height = $_POST['wpti_x']; //This is empty??? Hardcoded works fine
$width = $_POST['wpti_y']; //This is empty??? Hardcoded works fine
$prices = get_prices($width, $height, $backend_prod_id);
$json_string = json_encode($prices); //json encode prices
$obj = json_decode($json_string, true);
return $obj['product_price'];
}
check_ajax_referer( 'order-item', 'security' );
$item_to_add = sanitize_text_field( $_POST['item_to_add'] );
$order_id = absint( $_POST['order_id'] );
// Find the item
if ( ! is_numeric( $item_to_add ) ) {
die();
}
$post = get_post( $item_to_add );
if ( ! $post || ( 'product' !== $post->post_type && 'product_variation' !== $post->post_type ) ) {
die();
}
$_product = wc_get_product( $post->ID );
$order = wc_get_order( $order_id );
$order_taxes = $order->get_taxes();
$class = 'new_row';
// Set values
$item = array();
$item['product_id'] = $_product->id;
$item['variation_id'] = isset( $_product->variation_id ) ? $_product->variation_id : '';
$item['variation_data'] = $item['variation_id'] ? $_product->get_variation_attributes() : '';
$item['name'] = $_product->get_title();
$item['tax_class'] = $_product->get_tax_class();
$item['qty'] = 1;
$item['line_subtotal'] = new_prices($_product->id);
$item['line_subtotal_tax'] = '';
$item['line_total'] = new_prices($_product->id);
$item['line_tax'] = '';
// Add line item
$item_id = wc_add_order_item( $order_id, array(
'order_item_name' => $item['name'],
'order_item_type' => 'line_item'
) );
// Add line item meta
if ( $item_id ) {
wc_add_order_item_meta( $item_id, '_qty', $item['qty'] );
wc_add_order_item_meta( $item_id, '_tax_class', $item['tax_class'] );
wc_add_order_item_meta( $item_id, '_product_id', $item['product_id'] );
wc_add_order_item_meta( $item_id, '_variation_id', $item['variation_id'] );
wc_add_order_item_meta( $item_id, '_line_subtotal', $item['line_subtotal'] );
wc_add_order_item_meta( $item_id, '_line_subtotal_tax', $item['line_subtotal_tax'] );
wc_add_order_item_meta( $item_id, '_line_total', $item['line_total'] );
wc_add_order_item_meta( $item_id, '_line_tax', $item['line_tax'] );
// Since 2.2
wc_add_order_item_meta( $item_id, '_line_tax_data', array( 'total' => array(), 'subtotal' => array() ) );
// Store variation data in meta
if ( $item['variation_data'] && is_array( $item['variation_data'] ) ) {
foreach ( $item['variation_data'] as $key => $value ) {
wc_add_order_item_meta( $item_id, str_replace( 'attribute_', '', $key ), $value );
}
}
do_action( 'woocommerce_ajax_add_order_item_meta', $item_id, $item );
}
$item = apply_filters( 'woocommerce_ajax_order_item', $item, $item_id );
include( 'admin/meta-boxes/views/html-order-item.php' );
// Quit out
die();
}
?>
I cant figure out why it does not add the width ($_POST['wpti_x']) and height ($_POST['wpti_x']) to POST. If the values are hardcoded, it works fine.
Any help would be appreciated.
You will need to edit meta-boxes-order-min.js, as that is where the functionality you are trying to use exists in woocommerce.
If you want to POST those values, you may need to edit the add_item function.
I hope this helps, and remember if you update woocommerce, you edits will be lost. so this is really not advised.
I am using the Woocommerce Category Plugin, which enables the assignment of a banner image to a specific category, this is then brought out in the header of the page should the user be viewing a category page.
However I would like to also show the same banner once someone has clicked through on a specific product page.
The code of the plugin is below, I do hope someone can help or at least point me in the right direction.
Many Thanks in advance for all your input
Plugin code
<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
if ( ! class_exists( 'WCB_Category_Banner' ) ) :
class WCB_Category_Banner {
public function __construct() {
// Add Scripts and styles
add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts_and_styles' ) );
// Add the fields to the product cateogry taxonomy
add_action( 'product_cat_edit_form_fields', array( $this, 'wcb_product_cat_taxonomy_custom_fields' ), 10, 2 );
// Save the changes made on the product category taxonomy
add_action( 'edited_product_cat', array( $this, 'wcb_product_cat_save_taxonomy_custom_fields'), 10, 2 );
// Add a banner image based on category taxonomy image
add_action( 'woo_header_inside', array( $this, 'wcb_show_category_banner'), 30 );
}
/*
* Adds necessary admin scripts
*/
public function admin_scripts_and_styles() {
// Get current screen attributes
$screen = get_current_screen();
if ( $screen != null and $screen->id == "edit-product_cat" ) {
// Adds WP Modal Window References
wp_enqueue_media();
// Enque the script
wp_enqueue_script( 'wcb_admin_script',
plugin_dir_url( __FILE__ ) . 'assets/js/wcb-admin.js',
array('jquery'), '1.0.0', true
);
// Add Style
wp_enqueue_style(
'wcb_admin_styles',
plugins_url( '/assets/css/wcb-admin.css', __FILE__ )
);
}
}
/*
* Adds default option values
*/
public function wcb_product_cat_taxonomy_custom_fields( $tag ) {
// Check for existing taxonomy meta for the term you're editing
$t_id = $tag->term_id; // Get the ID of the term you're editing
$term_meta = get_option( "taxonomy_term_$t_id" ); // Do the check
// Get banner image
if ( isset( $term_meta['banner_url_id'] ) and $term_meta['banner_url_id'] != '' )
$banner_id = $term_meta['banner_url_id'];
else
$banner_id = null;
// Get banner link
if ( isset( $term_meta['banner_link'] ) and $term_meta['banner_link'] != '' )
$banner_link = $term_meta['banner_link'];
else
$banner_link = null;
?>
<tr class="form-field banner_url_form_field">
<th scope="row" valign="top">
<label for="banner_url"><?php _e('Banner Image'); ?></label>
</th>
<td>
<fieldset>
<a class='wcb_upload_file_button button' uploader_title='Select File' uploader_button_text='Include File'>Upload File</a>
<a class='wcb_remove_file button'>Remove File</a>
<label class='banner_url_label' ><?php if ( $banner_id != null ) echo basename( wp_get_attachment_url( $banner_id ) ) ?></label>
</fieldset>
<fieldset>
<img class="cat_banner_img_admin" src="<?php if ( $banner_id != null ) echo wp_get_attachment_url( $banner_id ) ?>" />
</fieldset>
<input type="hidden" class='wcb_image' name='term_meta[banner_url_id]' value='<?php if ( $banner_id != null ) echo $banner_id; ?>' />
</td>
</tr>
<tr class="form-field banner_link_form_field">
<th scope="row" valign="top">
<label for="banner_link"><?php _e('Banner Image Link'); ?></label>
</th>
<td>
<fieldset>
<input type="url" name='term_meta[banner_link]' value='<?php if ( $banner_link != null ) echo $banner_link ?>' />
<label class="banner_link_label" for="banner_link"><em>Where users will be directed if they click the banner.</em></label>
</fieldset>
</td>
</tr>
<?php
}
// A callback function to save our extra taxonomy field(s)
public function wcb_product_cat_save_taxonomy_custom_fields( $term_id ) {
if ( isset( $_POST['term_meta'] ) ) {
$t_id = $term_id;
$term_meta = get_option( "taxonomy_term_$t_id" );
$cat_keys = array_keys( $_POST['term_meta'] );
foreach ( $cat_keys as $key ){
if ( isset( $_POST['term_meta'][$key] ) ){
$term_meta[$key] = $_POST['term_meta'][$key];
}
}
//save the option array
update_option( "taxonomy_term_$t_id", $term_meta );
}
}
// Retreives and print the category banner
public function wcb_show_category_banner() {
global $woocommerce;
global $wp_query;
// Make sure this is a product category page
if ( is_product_category() ) {
$cat_id = $wp_query->queried_object->term_id;
$term_options = get_option( "taxonomy_term_$cat_id" );
// Ge the banner image id
if ( $term_options['banner_url_id'] != '' )
$url = wp_get_attachment_url( $term_options['banner_url_id'] );
// Exit if the image url doesn't exist
if ( !isset( $url ) or $url == false )
return;
// Get the banner link if it exists
if ( $term_options['banner_link'] != '' )
$link = $term_options['banner_link'];
// Print Output
if ( isset( $link ) )
echo "<a href='" . $link . "'>";
if ( $url != false )
echo "<div id=\"mainslider\"><img src='" . $url . "' class='category_banner_image' /></div>";
echo '
<div id="welcome" style="width:300px; min-height:210px;">
<div class="whitebanner">
<h2>Give Us a Call</h2></div>
<p class="welcometext"><strong>Janet Morley & Jill Perkins</strong></p>
<p class="welcomedetails">Tel: +44 (15395) 64247<br/>
Tel: +44 (16268) 88069<br/>
Mobile: +44 (77329) 26787<br/>
</p>
</div>
';
if ( isset( $link ) )
echo "</a>";
}
}
}
endif;
new WCB_Category_Banner();
?>
First you need to think on what happens if one product has many categories, and if it has, which one will display?
We need to create and array of category id's and randomly select one, right?
So:
Create an array to hold your id's
Get all categories of current product
Get one of this ids randomly
Obtain the corresponding banner off that id
$termArray = array();
$terms = get_the_terms($post->ID, "sectores");
//insert id's in to array
foreach ($terms as $id) {
$termArray[] = $id->term_id;
}
//get random id
$randomId = array_rand($termArray);
//final ID
$cat_id = $termArray[$randomId];
//Get values from database
$banner = get_option( "taxonomy_term_$cat_id" );
$url = wp_get_attachment_url( $banner['banner_url_id'] );
$link = $banner['banner_link'];
echo '<a href="'.$link.'">';
echo '<img src="'.$url.'">';
echo "<a>";