简体   繁体   中英

Change error notice text and make an action for this error in Woocommerce

I am not used to hooks in Wordpress and Woocommerce. I was wondering if it was possible to change an error notice text in Woocommerce using this dedicated filter hook:

add_filter('woocommerce_add_error', 'alter_check_for_afterpay', 100000);

function alter_check_for_afterpay($message) {

    //kijk of er in de foutmelding het woord afterpay in staat
    $find_afterpay = strpos($message, "AfterPay");

    if($find_afterpay == true){

         $message = "Helaas, is het niet gelukt om met AfterPay te betalen. U kunt uw order bestellen door ideal te gebruiken.";
         doSomeThing();
    }

    return $message;
}

function doSomeThing(){
    echo "Do something here";
}

I wanna do something when error is showing on the checkout page.

Updated - You should try to use instead the following code, but this error notice need to be processed through wc_add_notice() or wc_print_notice() functions to be functional.

Here is your revisited code:

add_filter('woocommerce_add_error', 'alter_check_for_afterpay', 990 );
function alter_check_for_afterpay( $message ) {

    if( strpos( $message, "AfterPay" ) !== false ){

         $message = __("Helaas, is het niet gelukt om met AfterPay te betalen. U kunt uw order bestellen door ideal te gebruiken.", "woocommerce");
    }
    return $message;
}

Code goes in function.php file of your active child theme (or active theme). Tested (with another word instead of "AfterPay") and works. It could work for you.

Your function doSomeThing() will not output anything using this filter hook, as it should need some specific action hook instead…

If you want to do something (an action), You will need to target this error logic in dedicated woocommerce_after_checkout_validation action hook, this way:

add_action('woocommerce_after_checkout_validation', 'alter_check_for_afterpay_action', 990, 2 );
function alter_check_for_afterpay_action( $data, $errors ) {
    foreach ( $errors->get_error_messages() as $message ) {
        if( strpos($message, "AfterPay") !== false )
        {
            // ===> do your action here (but not echoing something !)
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM