woocommerce add function when admin changes product's attributes - woocommerce

I am relatively new to woocommerce development so I am sorry if this question might be too trivial but I need help.
I need in my application a way to make some checks when an admin makes changes to a product in woocommerce.
For example, I want to create a log file of all the changes that occurred on products. Who made them, when and what was the change (price, inventory, description, etc.).
I understand that there are hooks in woocommerce that I can use. Which ones can help me do something like that?

Use post_updated hook for this purpose, place the following code in your functions.php
function product_update_handler( $id, $before_data, $after_data ) {
if( $before_data->post_type == "product" ) {
$current_user = wp_get_current_user();
error_log( $before_data->post_title ." has been updated by ".$current_user->user_login );
}
}
add_action('post_updated', 'product_update_handler', 0, 3);
you have two product objects ( before update, after update ) with the above hook, you can compare both object and log the changes.

Related

Woocommerce : How to add a custom meta_key to checkout billing_phone?

I want to enter the value of digits_phone meta key to be entered as billing_phone for every woocommerce order.
I came up with something like this but it did not work :
//Automatically add the digits phone number of the user, to woocommerce orders for every order
add_filter('woocommerce_checkout_posted_data', 'dg_manipulate_checkout_posted_data');
function dg_manipulate_checkout_posted_data ($data) {
$data['billing_phone'] =['digits_phone'];
return $data;
}
can anyone please help me to figure this out?
I have never used the plugin myself, take this as a guideline
THIS CODE IS NOT TESTED !
Maybe this question is a better fit for wordpress.stackexchange.com
From the last comment of this post I see that there should be 2 user metadata related to some digits_phone: 'digits_phone' and 'digits_phone_no'
Assuming that the one we want is digits_phone, this code should be a hint in the right direction:
add_filter('woocommerce_checkout_posted_data', 'dg_manipulate_checkout_posted_data');
function dg_manipulate_checkout_posted_data ($data) {
// save current user data in variable $current_user
$current_user = wp_get_current_user();
//get digits phone from db and save in variable $digits_phone
$digits_phone = get_user_meta( $current_user->ID, 'digits_phone' , true );
// assign to POSTed array and return it
$data['billing_phone'] = $digits_phone;
return $data;
}
Also have a look at How can I convert woocommerce checkout fields in capital letters to get a better picture of manipulating POST data

Save custom fields to user meta on WooCommerce Checkout for new user who is registering on checkout

I have added several custom fields to my checkout that only appear when a user is checking out as a guest for the first time. My checkout process requires that the user create an account to complete checkout.
I have added four fields using the woocommerce_form_field method and then I have tried modifying the code provided in the answer here to achieve what I want. However, I have tried several checkouts, creating new accounts to check if the custom field values save into the new users' profile, but it doesn't seem to be working.
Here is one example of a solution I tried which did not work:
function reigel_woocommerce_checkout_update_user_meta( $customer_id) {
if ( ! empty( $_POST['practitioner_license_number'] ) ) {
$pln = sanitize_text_field( $_POST['practitioner-license-number'] );
update_user_meta($customer_id, 'practitioner_license_number', $pln);
}
}
add_action('woocommerce_created_customer', 'reigel_woocommerce_checkout_update_user_meta', 10, 2);
practitioner-license-number is my custom field added using the woocommerce_form_field method. I modified the code at the link above, so that the function runs on woocommerce_created_customer and then in update_user_meta I'm trying to pass the customer ID so that it saves the meta to the user profile that is created.
Would appreciate help trying to solve this. Most of the questions/answers on this subject assume that the user is logged in and already has an account, which is not the case here.
From the code you share, I think the problem lies in incorrectly passing to the $_POST,
perhaps practitioner_license_number vs practitioner-license-number.
You can use the code below to see if your hook works, if the value is written in the database you know that the problem is indeed elsewhere.
It might help to share the code you used for the custom fields too?
function action_woocommerce_created_customer( $customer_id, $new_customer_data, $password_generated ) {
$pln = 'test';
update_user_meta( $customer_id, 'practitioner_license_number', $pln);
}
add_action( 'woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3 );

How to get Pay Now URL with custom order status in WooCommerce?

I want to get the URL from where the customer can directly pay for their Invoice and also it should work with wc-cancelled and wc-transaction-declined (custom order status).
My Solution
What I'm doing now is created a custom page with my custom get parameters and processing the whole Payment Process as Documentation in Gateway provider Website.
My Problem
But the problem is whenever they update their doc file and plugin I also have to update my code; but if I get the Pay Now URL then WooCommerce and Gateway Plugin will take care of it.
Is there a better solution?
I got the solution in WooCommerce templates/emails/customer-invoice.php file. The function that I was looking for is get_checkout_payment_url().
Usage
$order = wc_get_order($order_id);
$pay_now_url = esc_url( $order->get_checkout_payment_url() );
echo $pay_now_url; //http://example.com/checkout/order-pay/{order_id}?pay_for_order=true&key={order_key}
//http://example.com will be site_url and protocol will depending upon SSL checkout WooCommerce setting.
But this url only works with pending, failed order status; So I used filter woocommerce_valid_order_statuses_for_payment
if (!function_exists('filter_woocommerce_valid_order_statuses_for_payment')) {
//http://woocommerce.wp-a2z.org/oik_api/wc_abstract_orderneeds_payment/
//http://hookr.io/filters/woocommerce_valid_order_statuses_for_payment/
// define the woocommerce_valid_order_statuses_for_payment callback 
function filter_woocommerce_valid_order_statuses_for_payment( $array, $instance ) {
$my_order_status = array('cancelled', 'transaction-declined');
return array_merge($array, $my_order_status);
}
// add the filter 
add_filter('woocommerce_valid_order_statuses_for_payment', 'filter_woocommerce_valid_order_statuses_for_payment', 10, 2);
}
^^ I added this in my active theme's functions.php file.
Reference:
get_checkout_payment_url()
wc_abstract_orderneeds_payment
woocommerce_valid_order_statuses_for_payment
You can get url with below code but it will work for wc-pending status order only, with the help of order_id or post_id
$order = wc_get_order($order_id);
echo $pay_now_url = $order->get_checkout_payment_url();

Wordpress: Change user role conditionally

I am creating a Wordpress website for multi author and want to set user role as per article submission. Means if any user have 0-10 article they will go to Contributor role, if 11-30 will go to Author role if 31-100 will go to Editor role.
Also I want to make registration system where default registration group will be Subscriber. They will get a link into verification email like
If you want to become a Contributor please click on below link. (To submit an article you must have at least Contributor permission)
http:// link will be here ... this link automatically change user role from Subscriber to Contributor.
Hope I will get solution from you expert. I am posting this issue with lots of hope from you friends.
What you want to do is when they post their submission check to see how many posts they have authored and then change the role. So in your theme's functions.php file you'd need a hook that is like this.
add_action('publish_post', 'update_roles');
and then a function to update the roles.
function update_roles()
{
global $wpdb;
// Get the author
$author = wp_get_current_user();
// Not sure if $author and $u are the same object I suspect they are.
// so this may not be necessary, but I found this code elsewhere.
// You may be able to do without this and just replace $u with $author later in the code.
// Get post by author
$posts = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_author = " . $author->ID );
$numPost = count($posts);
// Do the checks to see if they have the roles and if not update them.
if($numPost > 0 && $numposts <= 10 && current_user_can('subscriber'))
{
// Remove role
$author->remove_role( 'subscriber' );
// Add role
$author->add_role( 'contributor' );
}
...... other conditions .......
}
Using SQL statements (Database Queries) to get at Wordpress data is not in accordance with Wordpress coding standards . See Wordpress Handbook
It would be better to use count_user_posts function
See Function on the codex

How can I add custom meta fields in categories?

Does anyone have any idea how to add custom meta fields while making categories and fetch them in the loop in WordPress? I was wondering how to do that without hacking the WordPress core, but if I do – it won't become a hindrance to update WordPress in the future.
A plugin I have found that comes close is Wp-Category-Meta, but it doesn't have the ability to add checkboxes as fields in Edit Categories.
This will be very useful as users can make certain categories "featured", and then the code can use that meta value in the loop to style "featured" categories differently.
The problem:
Wordpress does not have a structure nor method to store "meta" values for taxonomies.
UPDATE 2017: WP 4.4+ has "term meta"!
For working with term metas use these:
update_term_meta()
get_term_meta()
delete_term_meta()
add_term_meta()
The Actions below are still valid though! :)
Additional reading: 4.4 Taxonomy Roundup
Solution for WP version <= 4.3.x and COMMON actions
Actions:
create_category and edit_category for category edit
category_add_form_fields and category_edit_form for category form fields
There are more actions than I've presented, but they seem to be deprecated (according to developer.wordpress.org).
The reason I chose the actions that I chose:
- They work on WordPress 4.4.2
- Due to lack of documentation I assumed these are the new ones replacing the deprecated ones...
Functions:
get_option( $option, $default );
update_option( $option, $new_value, $autoload );
update_option has two great abilities:
a) It craetes the option when such option does not exist yet
Unless you need to specify the optional arguments of add_option(),
update_option() is a useful catch-all for both adding and updating
options.
b) $new_value can be an integer, string, array, or object.
You may ask, why to use array/object? ...well, because each option = 1 database row => you probably want to store your category options in one row :)
The CODE
function my_category_form_fields($tag_object){
//output/display extra form fields, e.g. by echo ...
//ADD EXTRA SPECIFIC FIELD TO LATER CHECK IF IT'S CATEGORY SAVE/EDIT!
//(see note at 'edit_category' action...)
if( !empty($tag_object['term_id']) ){
//edit category form specific
//...load existing options with get_option( $option, $default );
} else {
//create category form specific
}
}
function my_category_save(){
//CHECK FOR YOUR EXTRA SPECIFIC FIELD TO CHECK IF IT'S CATEGORY SAVE/EDIT
//(see note at 'edit_category' action...)
//SECURITY CHECK
if( empty($_POST['EXTRA_SPECIFIC_FIELD']) || ! current_user_can('manage_categories') )
return null;
//save your form values using update_option()
//Recommendation:
//Add "category_" prefix and $category_id to your option name!
}
add_action( 'create_category', 'my_category_save', 10, 1 );
//Runs when a category is updated/edited,
//INCLUDING when a post or blogroll link is added/deleted or its categories are updated
//(which causes the count for the category to update)
add_action( 'edit_category', 'my_category_save', 10, 1 );
add_action( 'category_add_form_fields', 'my_category_form_fields', 10, 1 );
add_action( 'category_edit_form', 'my_category_form_fields', 10, 1 );
Create or Edit?
You might wonder whether you are creating or saving a category - this not documented yet (as far as I know), but from testing:
Edit save => $tag_object is object and contains some properties, most notably:
term_id
taxonomy
filter
Create save => $tag_object is just a regular string "category" - I guess this might change in the future...
General taxonomy
There are also actions like these for taxonomies in general - check these actions.
Jaz,
It looks like the plugin you mention in your original question has been updated to include a checkbox field (included in v1.2.3)
I think the Category SEO Meta Tags plugin will help you.
There is an updated and refactured version of this plugin to be found here:
https://wordpress.org/plugins/custom-taxonomy-category-and-term-fields/
Also added a WYSIWYG editor fieldtype.

Resources