woocommerce coupons description in order email - wordpress

I've got a problem to show coupon description in thank you order mail.
I have name of coupon by using:
$order->get_used_coupons()
But above function returns only namen. Any one know how to get description for specific coupon name?

Try this code:
$coupons = $order->get_items( 'coupon' );
foreach ( $coupons as $item_id => $item ) {
echo "<span class='coupon-name'><b>".$item['name']."</b></span>";
$post = get_post( $item_id );
echo "<p class='coupon-description'>".$post->post_excerpt."</p>";
}
}

Related

Redirecting customers to custom page after sale in WooCommerce

I'm trying to learn WooCommerce and WordPress plugins so I'm tweaking around. I'm trying to create a plugin that redirects customer to a custom page after checkout. The custom page/url can be defined when I create the product. Here is my code:
<?php
/*
Plugin Name: Custom Redirect After Sale
Description: Redirects customers to a custom page after a successful sale.
*/
// Register a new meta field for products
add_action( 'add_meta_boxes', 'custom_redirect_meta_box' );
function custom_redirect_meta_box() {
add_meta_box( 'custom_redirect_meta_box', 'Custom Redirect URL', 'custom_redirect_meta_box_callback', 'product', 'side' );
}
function custom_redirect_meta_box_callback( $post ) {
$value = get_post_meta( $post->ID, '_custom_redirect_url', true );
echo '<label for="custom_redirect_url">Custom Redirect URL:</label>';
echo '<input type="text" id="custom_redirect_url" name="custom_redirect_url" value="' . esc_attr( $value ) . '" style="width:100%">';
}
// Save the meta field value when the product is saved
add_action( 'save_post_product', 'save_custom_redirect_meta_box_data' );
function save_custom_redirect_meta_box_data( $post_id ) {
if ( isset( $_POST['custom_redirect_url'] ) ) {
update_post_meta( $post_id, '_custom_redirect_url', sanitize_text_field( $_POST['custom_redirect_url'] ) );
}
}
// Redirect to the custom page after a successful sale
add_action( 'woocommerce_payment_complete', 'custom_redirect_after_sale' );
function custom_redirect_after_sale( $order_id ) {
$order = wc_get_order( $order_id );
//$order->update_status( 'completed' );
$items = $order->get_items();
// Get the first product in the order
$product = reset($items);
// Get the custom redirect URL for the product
//$redirect_url = get_post_meta( $product->get_product_id(), '_custom_redirect_url', true );
$redirect_url = get_post_meta( $product->get_id(), '_custom_redirect_url', true );
//echo "Meta retrieved: " . $redirect_url;
//error_log("callback fired");
//echo "Payment complete ho ho ho";
if( $redirect_url ) {
wp_redirect( $redirect_url );
exit;
}
}
It seems the woocommerce_payment_complete hook is not firing. I tried to echo out the redirect url and text but it doesn't seem to work.
I'm on localhost and I'm using the cash on delivery payment method.
Basing this answer on the great https://rudrastyh.com/ - specifically this tutorial https://rudrastyh.com/woocommerce/thank-you-page.html#redirects this is the code that should work for what you are trying to do.
First, you hook into the template_redirect action to determine the URL where the customer needs to go
Getting the Order ID, you can get the products purchased for that order
Once you have the purchased products, you can get their ID and meta data, the redirect URL you saved for each. Note that while you use WP functions for handling meta, when working with WooCommerce it is best practice to use its CRUD methods. In case in the future they port products to custom tables, your code will continue working.
Implement the redirect with the WP function wp_safe_redirect
Note that what you are trying to achieve will have problems if customers purchase orders with more than 1 product, and you have more than 1 redirect URL. In this implementation, the first product in the order that has a saved redirect URL will override all others
add_action( 'template_redirect', 'purchased_product_redirect');
function purchased_product_redirect(){
if( !function_exists( 'is_wc_endpoint_url' )){
return;
}
// do nothing if we are not on the order received page
if( ! is_wc_endpoint_url( 'order-received' ) || empty( $_GET[ 'key' ] ) ) {
return;
}
// Get the order ID
$order_id = wc_get_order_id_by_order_key( $_GET[ 'key' ] );
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Get and Loop Over Order Items
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$product = wc_get_product($product_id);
if(!$product){
continue;
}
//Get the first product's redirect URL
$product_redirect_url = $product->get_meta('_custom_redirect_url');
if(!$product_redirect_url){
continue;
}
wp_safe_redirect( $product_redirect_url );
exit; // always exit after using wp_safe_redirect
}
}

WooCommerce display variable product attributes

I am trying to display attributes of a particular product (i.e. id: 459) that has multiple variations and trying to display some of the attributes (i.e. name, id, link to the product and image) on the index page. I managed to get the variation image and id, however now trying to find it difficult to display the URL to the product and display variable product name.
I tried to look on the net for an answer but couldn't find it even codex or documentation. Can someone please help?
This is my working code, showing the image and id perfectly fine.
<?php
$product = new WC_Product_Variable( '459' );
$variations = $product->get_available_variations();
foreach ( $variations as $variation ) {
echo "<img src=" . $variation['image']['thumb_src'] .">";
echo $variation['variation_id'];
echo $variation['variation_Name ']; // (Error: "Notice: Undefined index: variation_Name in /var/www/wp-content/themes/...")
}
?>
Thank you for your help in advance.
EDIT
This is my code, everything works perfectly apart from not getting the attribute name.
I am getting this error message: Array to string conversion in /var/www/wp-content
<?php
$product = new WC_Product_Variable( '459' );
$variations = $product->get_available_variations();
foreach ( $product->get_variation_attributes() as $attribute_name => $ {
$attributes[] = array( 'name' => ucwords( str_replace( 'attribute_', '',
wc_attribute_taxonomy_slug( $attribute_name ) ) ),
'option' => $attribute, );
echo $attribute;
}
foreach ( $variations as $variation ) {
echo '<div class="col-3">';
echo '<a href="'.$product->get_permalink().'#variations-table">';
echo $product->get_title();
echo "<img src=" . $variation['image']['thumb_src'] .">";
echo 'View Product</a>';
echo '</div>';
}
?>
Thank you soo much :)
/* try this below code instead*/
/* Get variation attribute based on product ID */
$product = new WC_Product_Variable( $product_id );
$variations = $product->get_available_variations();
$var_data = [];
foreach ($variations as $variation) {
if($variation[‘variation_id’] == $variation_id){
$var_data[] = $variation[‘attributes’];
}
}
/*Get attributes from loop*/
foreach($var_data[0] as $attrName => $var_name) {
echo $var_name;
}

adding shipping calculator to woocommerce order page

In Woocommerce on the "edit order" page, is there any way to display all of the shipping methods and their costs for that order? A bit like the shipping calculator the customer sees on the cart page or checkout page, but on the edit order page instead?
Or alternatively, to add all of the items and customer shipping postcode etc from the order back to a new cart session so we can see the shipping caclulator in the cart page using this data?
extracting the products from the order using something like:
$order_items = $order_object->get_items( array('line_item', 'fee', 'shipping') );
if ( !is_wp_error( $order_items ) ) {
foreach( $order_items as $item_id => $order_item ) {
echo $order_item->get_quantity(); // or $order_item['quantity'];
echo $order_item->get_product_id(); // or $order_item['product_id'];
echo $order_item->get_variation_id(); // or $order_item['variation_id'];
echo $order_item->get_product(); // get the associated product
}
}
And then wp_create_order() to add those to a new cart?
Many thanks
I found this code, would this work with the modern version of woocommerce?
// Post variables
$order_id = isset($_POST['order_id'])?$_POST['order_id']:0;
$country = isset($_POST['country'])?$_POST['country']:0;
$state = isset($_POST['state'])?$_POST['state']:0;
$postcode = isset($_POST['postcode'])?$_POST['postcode']:0;
$city = isset($_POST['city'])?$_POST['city']:0;
// Order and order items
$order = wc_get_order( $order_id );
$order_items = $order->get_items();
// Reset shipping first
WC()->shipping()->reset_shipping();
// Set correct temporary location
if ( $country != '' ) {
WC()->customer->set_billing_location( $country, $state, $postcode, $city );
WC()->customer->set_shipping_location( $country, $state, $postcode, $city );
} else {
WC()->customer->set_billing_address_to_base();
WC()->customer->set_shipping_address_to_base();
}
// Remove all current items from cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
WC()->cart->empty_cart();
}
// Add all items to cart
foreach ($order_items as $order_item) {
WC()->cart->add_to_cart($order_item['product_id'], $order_item['qty']);
}
// Calculate shipping
$packages = WC()->cart->get_shipping_packages();
$shipping = WC()->shipping->calculate_shipping($packages);
$available_methods = WC()->shipping->get_packages();

Save WooCommerce Order Product Name to User Meta Custom Field

Caveat: I'm a solo freelance designer not a developer ;-)
I've created a custom field in the Wordpress user meta called membership.
I've tried the following code to save the WooCommerce Product Name to the membership custom field on checkout with help from this answer.
Updated attempt:
function wascc_woocommerce_checkout_update_user_meta_membership ( $customer_id, $posted ) {
if (isset($posted['$orderid'])) {
$order = $posted['$orderid'];
}
$theorder = new WC_Order( $order );
$items = $theorder->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
}
if (!(empty($product_name))) {
update_user_meta( $customer_id, 'membership', $product_name);
}
}
add_action( 'woocommerce_checkout_update_user_meta', 'wascc_woocommerce_checkout_update_user_meta_membership', 10, 2 );
It produces no error, but does not save the product name to membership.
Help appreciated.
Last question may be related.
as I've commented out, you should use woocommerce_checkout_update_order_meta.
Something like this:
function wascc_woocommerce_checkout_update_user_meta_membership ( $order_id ) {
$theorder = new WC_Order( $order_id );
$items = $theorder->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
}
if (!(empty($product_name))) {
// Gets the customer/user ID associated with the order. Guests are 0.
$customer_id = $theorder->get_user_id();
update_user_meta( $customer_id, 'membership', $product_name );
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'wascc_woocommerce_checkout_update_user_meta_membership' );
I have doubts with your foreach loop though... you are looping just to get the last item?

Woocommerce - How to get Cart item details from Functions.php

I am adding a condition based surcharge on the cart page but can't work out how to retrieve the meta details for the cart items.
If I do the following I get the item name, quantity & cost.. but how do I get the extra meta info?
$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) {
$_product = $values['data']->post;
echo "<b>".$_product->post_title.'</b> <br> Quantity: '.$values['quantity'].'<br>';
$price = get_post_meta($values['product_id'] , '_price', true);
echo " Price: ".$price."<br>";
}
Is there some code like
$items = $woocommerce->cart->get_cart_items_details();
or maybe the answer lies deeper in the array.. ?
Any help much appreciated.

Resources