I am trying to add some download permissions to all previous orders via a script to do them in batch. The script seems to work fine expect for one thing. Here is the script…
function update_download_permissions(){
$orders = get_posts( array(
'post_type' => 'shop_order',
'post_status' => 'wc-completed',
'posts_per_page' => -1
) );
foreach ( $orders as $order ) {
wc_downloadable_product_permissions( $order->ID, true );
}
}
The problem is the wc_downloadable_product_permissions function is producing duplicate entries in the wp_woocommerce_downloadable_product_permissions table.
I tried to set the second argument to false (the default) but that resulted in no permissions being created.
Does anybody have any ideas as to why duplicate download permissions are being set?
Cheers!
I came across your question after digging through some of the WooCommerce source code, while attempting to add an item to an existing order and then regenerate the permissions.
The reason wc_downloadable_product_permissions() will create duplicate permission entries is because it does not check for any existing permissions. It simply inserts another entry into the permissions table for every item in the order, which is no good because this will then show up as another download in both the admin and user account frontend.
The second force parameter (poorly documented), is related to a boolean flag that indicates whether wc_downloadable_product_permissions() has run before. The boolean is set to true at the end of the function via the set_download_permissions_granted method. If force is true, it will ignore the boolean. If force is false, and the boolean is true, the function will return near the start.
I created this function which uses the same functions as used by the admin Order action "Regenerate download permissions":
/**
* Regenerate the WooCommerce download permissions for an order
* #param Integer $order_id
*/
function regen_woo_downloadable_product_permissions( $order_id ){
// Remove all existing download permissions for this order.
// This uses the same code as the "regenerate download permissions" action in the WP admin (https://github.com/woocommerce/woocommerce/blob/3.5.2/includes/admin/meta-boxes/class-wc-meta-box-order-actions.php#L129-L131)
// An instance of the download's Data Store (WC_Customer_Download_Data_Store) is created and
// uses its method to delete a download permission from the database by order ID.
$data_store = WC_Data_Store::load( 'customer-download' );
$data_store->delete_by_order_id( $order_id );
// Run WooCommerce's built in function to create the permissions for an order (https://docs.woocommerce.com/wc-apidocs/function-wc_downloadable_product_permissions.html)
// Setting the second "force" argument to true makes sure that this ignores the fact that permissions
// have already been generated on the order.
wc_downloadable_product_permissions( $order_id, true );
}
I found the best way to update order download is to hook into the save_post action hook and check if it's a product that's being updated
there you can get order ids by product id and update just orders that relate to that specific product.
it's more efficient
function get_orders_ids_by_product_id($product_id) {
global $wpdb;
$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
return $wpdb->get_col(
"
SELECT DISTINCT woi.order_id
FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p
WHERE woi.order_item_id = woim.order_item_id
AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses )
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value LIKE '$product_id'
ORDER BY woi.order_item_id DESC"
);
}
// if you don't add 3 as as 4th argument, this will not work as expected
add_action('save_post', 'prefix_on_post_update', 10, 3);
function prefix_on_post_update($post_id, $post, $update) {
if ($post->post_type == 'product') {
$orders_ids = get_orders_ids_by_product_id($post_id);
foreach ($orders_ids as $order_id) {
$data_store = WC_Data_Store::load('customer-download');
$data_store->delete_by_order_id($order_id);
wc_downloadable_product_permissions($order_id, true);
}
}
}
Related
I am working on return processes in Woocommerce. I am getting returned or not returned information from table named return_table. I added this information to a new column in the orders table. The table is simply as follows:
I need to make changes to the column I just added. For example, I want to update the value from no return to returned. For this, I should make a new definition in the default actions column or add a new bulk action. I decided to add bulk action as it is more functional:
However, I was unable to make any progress after that. I've done research on Stackoverflow or other platforms. I found an answer to add buttons (new actions) but still couldn't solve the problem:
Source-1
Others I've found are mostly geared towards changing the "Order Status":
Source-2, Source-3, Source-4...
So, i've been researching this for a while and haven't found a solution. I will be grateful if anyone can help.
My Code:
<?php
// Add new column
add_filter( 'manage_edit-shop_order_columns', 'return_column', 11);
function return_column( $columns ) {
$columns['return_column'] = 'Return Status';
return $columns;
}
// Add the data to the custom columns
add_action( 'manage_shop_order_posts_custom_column', 'return_column_content',11);
function return_column_content ($column){
if($column == 'return_column'){
// Create required global variables
global $post, $wpdb;
$order = wc_get_order( $post->ID );
$order_id = $order->get_id();
$result = $wpdb->get_results("SELECT return_status FROM {$wpdb->prefix}return_table WHERE order_id ='$order_id' LIMIT 1");
if(count($result)):
echo $result[0]->return_status;
else:
echo '-';
endif;
}
}
//Add new order status to bulk change
add_filter( 'bulk_actions-edit-shop_order', 'refund_register_bulk_action' );
function refund_register_bulk_action( $bulk_actions ) {
$bulk_actions['mark_returned'] = 'Returned';
$bulk_actions['mark_not_returned'] = 'Not Returned';
return $bulk_actions;
}
I have setup a fresh docker container with Wordpress 5.0.3 and the latest WC and WC Eway plugin (WooCommerce eWAY Gateway).
Created a store with some products, hooked up my Eway sandbox environment, enabled Save Cards (which would enable the token) and created an order.
After checking the post_meta in my DB for the order, I didn't see a _eway_token_customer_id field. While being logged in as a customer, I tried again and with the new order I still do not get a token.
The reason for this tests is that I got this strange behaviour in my real, new website, where the first order with a NEW customer, doesn't result in a token.
However, when I create a second order whilst being logged in, I do get a _eway_token_customer_id value within the order_meta.
It is imperative for me to get that token with the first order, because after that I will auto renew the product using the tokenp ayment option.
Debugging this issue is hell, and I find it very disconcerting that on my fresh WP installation I get no token at all.
Is there anyone that has a bright idea?
**update
After some digging around in the Eway Plugin, I found out that the first time I do an order, the function request_access_code() from the class WC_Gateway_EWAY is checking if there is a token in the database for this user.
The function body:
protected function request_access_code( $order ) {
$token_payment = $this->get_token_customer_id( $order );
if ( $token_payment && 'new' === $token_payment ) {
$result = json_decode( $this->get_api()->request_access_code( $order, 'TokenPayment', 'Recurring' ) );
} elseif ( 0 === $order->get_total() && 'shop_subscription' === ( version_compare( WC_VERSION, '3.0', '<' ) ? $order->order_type : $order->get_type() ) ) {
$result = json_decode( $this->get_api()->request_access_code( $order, 'CreateTokenCustomer', 'Recurring' ) );
} else {
$result = json_decode( $this->get_api()->request_access_code( $order ) );
}
if ( isset( $result->Errors ) && ! is_null( $result->Errors ) ) {
throw new Exception( $this->response_message_lookup( $result->Errors ) );
}
return $result;
}
The function handles three possible outcomes:
1) new customer: results in calling `$this->get_api()->request_access_code( $order, 'TokenPayment', 'Recurring' )` <-- this is the one we are after!
2) shop_subscription: calls `$this->get_api()->request_access_code( $order, 'CreateTokenCustomer', 'Recurring' )`
3) else..: calls `$this->get_api()->request_access_code( $order )`
What is happening during debugging, is that the $token_payment variable has the value of an empty string for a new customer, instead of new.
So I will attempt to fix this, either via a filter/action hook, or figure out why this is happening.
When I forced the function the always use the first if block, I got my token. :)
**Update 2:
I tested with an existing user account, created a new order.
When I look in the post_meta table:
Voila, the new value is present.
However, when I am not logged in and I create an account, the new value is not added and that is where it goes wrong.
A temp fix would be to use a hook and add the new value to the order so that when get_token_customer_id is called it retrieves a new value and not an empty string.
I think this is a bug, since this value should be added. It explains why the second transactions get the token but not the first.
If only Woocommerce Eway plugin had a git repo.... I could flag an issue or fork it.
***Solution without hack
Added this to my plugin (or functions.php if you like):
add_action( 'woocommerce_checkout_order_processed', function( $order_id, $posted_data, $order ) {
update_post_meta( $order_id, '_eway_token_customer_id', 'new' );
}, 10, 3);
This will add the new value when you checkout with a non-existent user.
The token was added nicely after adding my creditcard details.
The matter of the fact stays that the plugin still has a bug, which you can work around.
I am using the following code to solve this but this is not working for orders from guest customers . However this is working fine for the orders belonging to some registered user/customer but not for the orders belonging to guest customers.
Solution credit to LoicTheAztec for answer
function cristmas_bulk_editing_orders(){
if(!is_admin()) return; // Will work only from Admin Backed.
else {
$order_id = 9458;
$new_customer_id = 479;
// Getting the postmeta customer ID for 'order' post-type
$customer_id = get_post_meta( $order_id, '_customer_user', true );
var_dump($customer_id);
// If it's an existing order and doesn't have already this user ID
// It update the customer ID
if( !empty($customer_id) && $new_customer_id != $customer_id )
update_post_meta($order_id, '_customer_user', $new_customer_id,0);
echo 'order updated';
}
}
cristmas_bulk_editing_orders();
ORIGINAL ISSUE
We imported the orders via woocommerce order export & import plugin from woocommerce team ..
But in the process something went wrong.. Most of the orders were not assigned any customer ..
So now when ever a new customer registers he/she is assigned 1 of these orders automatically ..
So basicallly all of them see 1 order in their recent orders which belongs to some other guest cusotmer , then they have all the information about other customer . their email etc..
So one option is I find out all the orders(with issues that is no customer assisned to them ) and I assign them to admin ..but this also have some issuses.....
SO is there any other option that these new registered users don't get old orders assigned..
Please help
May be you could try this other similar function based on SQL queries, that should do the trick. Before starting, make a database backup. I have add controls (or limitations) like :
A max date (in YYYY-MM-DD 00:00:00 date time format)
Order number range
So here is that code:
function easter_bulk_editing_orders(){
if( ! is_admin() ) return; // Will work only from Admin Backed.
else {
$processed_orders = array();
// Define the replacement user ID
$replacement_user_id = '2500';
// Define the DATE LIMIT for guest orders max date limit
$max_date = '2017-12-09 00:00:00';
// Define an order range
$order_id_min = '0';
$order_id_max = '100000';
global $wpdb;
// Get all guest orders below a defined max date
$old_guest_orders = $wpdb->get_results( "
SELECT pm.*, p.post_date
FROM {$wpdb->prefix}postmeta AS pm
LEFT JOIN {$wpdb->prefix}posts AS p ON pm.post_id = p.ID
WHERE pm.post_id BETWEEN $order_id_min AND $order_id_max
AND pm.meta_key LIKE '_customer_user'
AND ( pm.meta_value LIKE '0' OR pm.meta_value LIKE '' )
AND p.post_date <= '$max_date'
" );
foreach( $old_guest_orders as $guest_order ){
$meta_id = $guest_order->meta_id;
$wpdb->query( "
UPDATE {$wpdb->prefix}postmeta as pm
SET pm.meta_value = '$replacement_user_id'
WHERE pm.meta_id = '$meta_id'
" );
// Set each order ID in an array
$processed_orders[] = $guest_order->post_id;
}
// Testing ( raw output of processed orders IDS )
var_dump($processed_orders);
}
}
// Run the function
easter_bulk_editing_orders();
Code goes in function.php file of your active child theme (active theme or in any plugin file).
You have to use this function only once and to remove it afterwards (see below).
USAGE:
Once this code is pasted and saved on function.php file, display or reload any Admin page from backend within your browser.
Now you can comment the function this way and save:
// easter_bulk_editing_orders();
Check that the orders have been changed as you want, and remove all this code.
Code is tested and works.
There is error in your importing so try to re-import. Have you tried WP All Import Premium. It will import anything with drag and drop titles, categories, and meta fields. you can also assign new meta name to post meta while importing. If you need more help then share more details.
I have written a custom "Edit Account" script that allows a Wordpress user to update their Wordpress account. Everything is working great, except that I can't seem to find a way to update the user's nicename, which also doubles as the user's URL slug (via the get_author_posts_url function). This is causing issues because when a user changes their name, their slug still contains their original name - not the new one.
I know that the sanitize_title function will generate the new nicename, but I don't know how to verify that it is unique and modify it if it is not before entering it into the DB. I am wondering what built-in functions Wordpress has to handle this. I know I can write my own script to do this, but I would much rather use Wordpress functions. I couldn't find this anywhere in the WP documentation. Thanks!
Here is a function I have written to in lue of a built in function:
function new_user_slug($string){
//GENERATE NEW SLUG
$slug=sanitize_title($string);
//MAKE SURE SLUG IS UNIQUE
$result=mysql_query("SELECT * FROM wp_users WHERE user_nicename='$slug'");
if(mysql_num_rows($result)==0){
return $slug;
}else{
$counter=2;
$kill=0;
while($kill==0){
$mod_slug=$slug."-".$counter;
$result=mysql_query("SELECT * FROM wp_users WHERE user_nicename='$mod_slug'");
if(mysql_num_rows($result)==0){
$kill=1;
}else{
$counter++;
}
}
return $mod_slug;
}
}
This takes a string (the user's updated name) and converts it into the default slug. It then checks the slug against the database to see if it is unique. If it is, the slug is returned. If not, it enters an iteration loop that incrementally changes the slug until it is unique.
Try this:
wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent )
Source: https://codex.wordpress.org/Function_Reference/wp_unique_post_slug
Actually if you use wordpress user functions like wp_insert_user and wp_update_user Wordpress itselt handles duplicate user_nicename entries and adds -n suffix to them.
So your code would be something like this:
function new_nicename( $user_id, $nicename ) {
$nicename = sanitize_title( $nicename );
$user_id = wp_update_user( array( 'ID' => $user_id, 'user_nicename' => $nicename ) );
}
I've been stuck trying to apply a Drupal commerce coupon for about 2 days now. I have taken care of validating the coupon and currently stumped when I'm trying to redeem it.
So inside my callback function I'm calling:
my_module_coupons_coupon_redeem($coupon);
And inside the redeem function I have:
function my_module_coupons_coupon_redeem($coupon) {
global $user;
$uid = $user->uid;
$order = commerce_cart_order_load($uid);
// Wrap the order for easy access to field data.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
// Create the new line item.
$line_item = commerce_coupon_line_item_new($coupon, $order->order_id);
$line_item->commerce_unit_price = array('und' => array(
'0' => array('amount' => 500, 'currency_code' => commerce_default_currency())
));
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
if (!is_null($line_item_wrapper->commerce_unit_price->value())) {
// Add the base price to the components array.
if (!commerce_price_component_load($line_item_wrapper->commerce_unit_price->value(), 'base_price')) {
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
$line_item_wrapper->commerce_unit_price->value(),
'base_price',
$line_item_wrapper->commerce_unit_price->value(),
TRUE
);
}
}
$line_item_wrapper->commerce_total->data = $line_item_wrapper->commerce_unit_price->data;
//$line_item_wrapper->commerce_product->data = $coupon;
// Save the line item now so we get its ID.
commerce_line_item_save($line_item);
// Add it to the order's line item reference value.
$order_wrapper->commerce_line_items[] = $line_item;
commerce_order_save($order);
}
The coupon line_item is being saved on the DB but when I refresh the cart page I get the following error:
EntityMetadataWrapperException: Unknown data property commerce_product. in EntityStructureWrapper->getPropertyInfo()
Just wondering if this is the correct way of applying coupons without the use of Rules and should I be saving it as a line item in the first place?
Take a look in sites/all/modules/commerce_coupon/oncludes/commerce_coupon.checkout_pane.inc
global $user;
$uid = $user->uid;
$error = '';
// load the cart
$order = commerce_cart_order_load($uid);
// load the coupon from the coupon code
// see MySQL -> your-schema, table: commerce_coupon, column: code
$coupon = commerce_coupon_redeem_coupon_code($code, $order, $error);
// 302 to the cart
drupal_goto('checkout/' . $order->order_id);
I realized this was posted a few years ago, but there was no working answer and I still couldn't find a complete solution for it anywhere.
After you've added the line item you still need to add the commerce coupon reference to the order like so:
$order_wrapper->commerce_coupon_order_reference[] = $coupon;
This way it won't get removed when commerce_coupon_commerce_cart_order_refresh() runs.