Woocommerce validate checkout function error on pageload - wordpress

I am making a custom validation process for a client, but it depends on country. In the Netherlands, one can use IDIN for this.
So i need to do a check in the checkout to find out if the country is "Netherlands". If that is the case, an extra field is needed to do the validation of the customer. This can be echo'ed via a shortcode.
So far i have the following:
function validate_country( $fields, $errors ){
$return = false;
if ( $fields[ 'billing_country' ] == 'Netherlands' ) {
$return = true;
$errors->add( 'validation', 'Please fill in the IDIN requirement' );
}
return $return;
}
add_action( 'woocommerce_after_checkout_validation', 'validate_country', 10,2 );
function print_idin_form() {
if(validate_country()){
echo do_shortcode('[bluem_identificatieformulier]');
}
}
add_action('woocommerce_checkout_after_customer_details','print_idin_form');
However, when i use this, it throws an error on pageload because obviously, the validate_country function is not executed yet. The error I get is:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function validate_country(), 0 passed
How to solve this?

Related

Woocommerce - Problem with Snippet code specific payment method for local pickup shipping method, it provokes Fatal Error on log

I entered the code in functions.php that makes only one payment type appear for a chosen shipping method, the code entered was the one below,
add_filter( 'woocommerce_available_payment_gateways', 'my_custom_available_payment_gateways', 10, 1 );
function my_custom_available_payment_gateways( $available_gateways ) {
if( is_admin() ) return $available_gateways; // Only for frontend
$local_found = false; // Initializing
// Loop through chosen shipping method rates
foreach ( WC()->session->get( 'chosen_shipping_methods' ) as $chosen_shipping_rate_id ) {
if( strpos( $chosen_shipping_rate_id, 'local_pickup' ) !== false || strpos( $chosen_shipping_rate_id, 'local_delivery' ) !== false ) {
$local_found = true; // Local pickup/delivery found
break; // Stop the loop
}
}
// If Local pickup/delivery is the chosen shipping method
if( $local_found ) {
// Loop through available payment methods
foreach ( $available_gateways as $payment_method_id => $payment_label ) {
// Remove all payement methods except "cheque"
if ( 'cod' !== $payment_method_id ) {
unset( $available_gateways[$payment_method_id] );
}
}
}
I have Woocommerce 7 and unfortunately after entering this code I start receiving the following in the error log
2022-10-29T18:40:51+00:00 CRITICAL Uncaught Error: Call to a member function get() on null in /home/autobrin/public_html/wp-content/themes/autobrinca/functions.php:777
Stack trace:
#0 /home/autobrin/public_html/wp-includes/class-wp-hook.php(307): my_custom_available_payment_gateways(Array)
#1 /home/autobrin/public_html/wp-includes/plugin.php(191): WP_Hook->apply_filters(Array, Array)
#2 /home/autobrin/public_html/wp-content/plugins/woocommerce/includes/class-wc-payment-gateways.php(163): apply_filters('woocommerce_ava...', Array)
#3 /home/autobrin/public_html/wp-content/plugins/woocommerce/src/Admin/Features/OnboardingTasks/Tasks/Payments.php(89): WC_Payment_Gateways->get_available_payment_gateways()
#4 /home/autobrin/public_html/wp-content/plugins/woocommerce/src/Admin/Features/OnboardingTasks/Tasks/Payments.php(70): Automattic\WooCommerce\Admin\Features\OnboardingTasks\Tasks\Payments::has_gateways()
#5 /home/autobrin/public_html/wp-content/plugins/woocommerce/src/Admin/Features/OnboardingTasks/Tasks/WooCommercePayments.php(92): Automattic\Wo em /home/autobrin/public_html/wp-content/themes/autobrinca/functions.php na linha 777
The code works perfectly but this error keeps popping up.
Any tips on what could be causing this situation?
I would be very grateful for any help :)
The code works perfectly but this error keeps popping up.
Any tips on what could be causing this situation?
I would be very grateful for any help :)

woocommerce_before_order_object_save hook not work [duplicate]

Hello I'm trying to create a function in the mu-plugins to prevent certain users to change order status from specific order statuses to specific order statuses.
I've been looking everywhere and I have tried many different ways, but nothing seems to work.
Actually the function is running using woocommerce_order_status_changed action hook. The thing is that this hook runs after the order status has already been changed, what's causing an infinite loop.
The most useful hook I found seems to be woocommerce_before_order_object_save.
I found "Add an additional argument to prevent 'woocommerce_order_status_changed' from being called" useful related thread on WooCommerce Github.
I tried using #kloon code snippet solution:
add_filter( 'woocommerce_before_order_object_save', 'prevent_order_status_change', 10, 2 );
function prevent_order_status_change( $order, $data_store ) {
$changes = $order->get_changes();
if ( isset( $changes['status'] ) ) {
$data = $order->get_data();
$from_status = $data['status'];
$to_status = $changes['status'];
// Do your logic here and update statuses with CRUD eg $order->set_status( 'completed' );
// Be sure to return the order object
}
return $order;
}
but $changes variable is always an empty array.
I tried to use wp_insert_post_data Wordpress hook, but when I set:
$data['post_status'] = "some status";
it just prevents the whole update (the whole new data) from being saved.
This is the code I would like to run is:
function($data){
if($data['order_status'] == 'comlpeted' && $data['new_order_status'] == 'proccessing'){
// prevent the order status from being changed
$data['new_order_status'] = $data['order_status'];
}
few more if conditions...
return $data;
}
Any help or advise is appreciated.
Based on #kloon code snippet, I have been able to get the old order status and the new order status. Then I can disable any status change from a specific defined order status to a specific defined order status.
With the following code, specific defined user roles can't change order status from "processing" to "on-hold":
add_filter( 'woocommerce_before_order_object_save', 'prevent_order_status_change', 10, 2 );
function prevent_order_status_change( $order, $data_store ) {
// Below define the disallowed user roles
$disallowed_user_roles = array( 'shop_manager');
$changes = $order->get_changes();
if( ! empty($changes) && isset($changes['status']) ) {
$old_status = str_replace( 'wc-', '', get_post_status($order->get_id()) );
$new_status = $changes['status'];
$user = wp_get_current_user();
$matched_roles = array_intersect($user->roles, $disallowed_user_roles);
// Avoid status change from "processing" to "on-hold"
if ( 'processing' === $old_status && 'on-hold' === $new_status && ! empty($matched_roles) ) {
throw new Exception( sprintf( __("You are not allowed to change order from %s to %s.", "woocommerce" ), $old_status, $new_status ) );
return false;
}
}
return $order;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

WordPress prevent delete taxonomy

I would like to prevent that some categories are accidentally deleted. For this I use a meta entry for the category to be protected.
I use the following code for this:
// edit: wrong hook! ** add_action( 'delete_term_taxonomy', 'taxonomy_delete_protection', 10, 1 );
add_action( 'pre_delete_term', 'taxonomy_delete_protection', 10, 1 );
function taxonomy_delete_protection ( $term_id )
{
if (get_term_meta ($term_id, 'delete-protect', true) === true)
{
wp_die('Cannot delete this category');
}
}
Unfortunately, instead of my error message, only "Something went wrong" is displayed. Why?
Edit: The `delete_term_taxonomy` is the wrong hook for my code, because it deleted the meta before i can check the meta entry. `pre_delete_term` does fire before anything happens with the category.
The "Why" is because of the following JavaScript that ships with WordPress:
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
/**
* Removes the term from the parent box and the tag cloud.
*
* `data.match(/tag_ID=(\d+)/)[1]` matches the term ID from the data variable.
* This term ID is then used to select the relevant HTML elements:
* The parent box and the tag cloud.
*/
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + wp.i18n.__( 'Sorry, you are not allowed to do that.' ) + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + wp.i18n.__( 'Something went wrong.' ) + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
The expected response to this POST request is:
'1' if the term was deleted
'-1' if your user doesn't have permission to delete the term.
For all other cases, "Something went wrong" is displayed.
You are terminating the script early with wp_die, yielding an unexpected response, which comes under "other cases".
There isn't a way to provide a custom error message in the notice box here without writing some JavaScript of your own.
This is my current solution, not perfect but it works.
The "Something went wrong" message show up if you delete the taxonomy with the row action. So i unset the "delete" action so it couldn't be triggered this way.
add_filter ('category_row_actions', 'unset_taxonomy_row_actions', 10, 2);
function unset_taxonomy_row_actions ($actions, $term)
{
$delete_protected = get_term_meta ($term->term_id, 'delete-protect', true);
if ($delete_protected)
{
unset ($actions['delete']);
}
return $actions;
}
Then i hide the "Delete" Link in the taxonomy edit form with css. It's still could be triggered if you inspect the site and it's link, but there is no hook to remove this action otherwise.
add_action( 'category_edit_form', 'remove_delete_edit_term_form', 10, 2 );
function remove_delete_edit_term_form ($term, $taxonomy)
{
$delete_protected = get_term_meta ($term->term_id, 'delete-protect', true);
if ($delete_protected)
{
// insert css
echo '<style type="text/css">#delete-link {display: none !important;}</style>';
}
}
Finally the check before deleting the taxonomy. This should catch all other ways, like the bulk action "delete". I didn't found another way yet to stop the script from deleting the taxonomy.
add_action ('pre_delete_term', 'taxonomy_delete_protection', 10, 1 );
function taxonomy_delete_protection ( $term_id )
{
$delete_protected = get_term_meta ($term_id, 'delete-protect', true);
if ($delete_protected)
{
$term = get_term ($term_id);
$error = new WP_Error ();
$error->add (1, '<h2>Delete Protection Active!</h2>You cannot delete "' . $term->name . '"!');
wp_die ($error);
}
}
This solution provides a way to disable all categories from being deleted by a non Admin. This is for anyone like myself who's been searching.
function disable_delete_cat() {
global $wp_taxonomies;
if(!current_user_can('administrator')){
$wp_taxonomies[ 'category' ]->cap->delete_terms = 'do_not_allow';
}
}
add_action('init','disable_delete_cat');
The easiest solution (that will automatically take care of all different places where you can possibly delete the category/term) and in my opinion the most flexible one is using the user_has_cap hook:
function maybeDoNotAllowDeletion($allcaps, $caps, array $args, $user)
{
if ($args[0] !== 'delete_term') return $allcaps;
// you can skip protection for any user here
// let's say that for the default admin with id === 1
if ($args[1] === 1) return $allcaps;
$termId = $args[2];
$term = get_term($termId);
// you can skip protection for all taxonomies except
// some special one - let's say it is called 'sections'
if ($term->taxonomy !== 'sections') return $allcaps;
// you can protect only selected set of terms from
// the 'sections' taxonomy here
$protectedTermIds = [23, 122, 3234];
if (in_array($termId, $protectedTermIds )) {
$allcaps['delete_categories'] = false;
// if you have some custom caps set
$allcaps['delete_sections'] = false;
}
return $allcaps;
}
add_filter('user_has_cap', 'maybeDoNotAllowDeletion', 10, 4);

woocommerce_email_recipient_customer_completed_order hook not being invoked

There are a bunch of example of using this woocommerce hook woocommerce_email_recipient_customer_completed_order. So I added it to functions.php, and concatenated a couple example recipients as a test, but only the purchaser receives an email. It doesn't seem like this filter is getting invoked since if I turn on debugging and error_log(...) there's nothing in the log file.
Is there a reason this isn't working? I tried bumping the priority up to 99, but that doesn't work either. The site uses all the defaults and doesn't override any of the templates.
add_filter( 'woocommerce_email_recipient_customer_completed_order', 'custom_woocommerce_add_email_recipient', 10, 2);
function custom_woocommerce_add_email_recipient($recipient, $order) {
$recipient = $recipient . ', foo#example.com, bar#example.com';
return $recipient;
}
As I learn more about Woocommerce it looks like this site only goes as far as processing so I had to use the customer_processing_order mail ID instead to get this to work (thanks to #LoicTheAztec for verifying the customer_completed_order hook works), and instead of using the woocommerce_email_recipient_customer_processing_order hook I used woocommerce_email_headers and checked the mail ID.
add_filter( 'woocommerce_email_headers', 'woocommerce_email_headers_add_recipient', 10, 3);
function woocommerce_email_headers_add_recipient($headers, $mail_id, $order) {
if($mail_id == 'customer_processing_order') {
$member = null;
$memberMail = null;
foreach($order->get_meta_data() as $item) {
if ($item->key === 'member_name') {
$member = $item->value;
$memberMail = $this->getMemberMail($member);
$headers .= "BCC: {$member} <{$member_mail}>\r\n";
break;
}
}
}
return $headers;
}

Get gravity forms fields

I am using the gravity form on my site. I am working on create the custom report for this I have need gravity form fields name and id based on specific form id.Please let me know how I can do it.
I am using the following function but it is showing all forms info based on it. it is looking very hard to parse it. Please let me know any function so I can get fields name easily.
$forms = RGFormsModel::get_forms_by_id(13);
try this
function get_all_form_fields($form_id){
$form = RGFormsModel::get_form_meta($form_id);
$fields = array();
if(is_array($form["fields"])){
foreach($form["fields"] as $field){
if(isset($field["inputs"]) && is_array($field["inputs"])){
foreach($field["inputs"] as $input)
$fields[] = array($input["id"], GFCommon::get_label($field, $input["id"]));
}
else if(!rgar($field, 'displayOnly')){
$fields[] = array($field["id"], GFCommon::get_label($field));
}
}
}
//echo "<pre>";
//print_r($fields);
//echo "</pre>";
return $fields;
}
It's not that hard to parse:
$fields=array();
foreach ( $forms['fields'] as $field ) {
$fields[]=array($field['id'] => $field['inputName']);
}
P.S. I'm assuming you use Gravity Forms < 1.7 as RGFormsModel::get_forms_by_id is a deprecated function since 1.7
// Get the Form fields
$form = RGFormsModel::get_form_meta($form_id);
// Run through the fields to grab an object of the desired field
$field = RGFormsModel::get_field( $form, $field_id );
I use the above to get a specific field I want to filter the value of. The $field contains an object with all the properties you want.
echo $field->label // Gets the label
echo $field->inputName // Gets the name
echo $field->type // Gets the type
echo $field->cssClass // Gets the CSS Classes as a string
You are able to get the entered value/content of a field by using rgpost() and by referencing the id ($field->id).
// Check the entered value of every field
foreach( $form['fields'] as &$field ) {
// Get the content for the specific field
$fieldContent = rgpost( "input_".$field->id );
// Check the content
if ( $fieldContent == ... ){}
}

Resources